发表于: 2020-05-27 18:45:11

1 1518


今天完成的事情:

研究了一下JDBCTemplate对数据库的查询功能:

1,查询数据库中单个基本数据类型(如String,Long,Integer等)和单个对象可以使用queryForObject()方法;

public <T> T queryForObject(String sql, Object[] args, Class<T> requiredType)

参数分别是sql,sql参数数组,返回数据类型。


2,查询基本数据类型列表可以使用queryForList()方法;

public <T> List<T> queryForList(String sql, Object[] args, Class<T> elementType)

参数分别是sql,sql参数数组,返回数据类型


3,查询单个对象可以使用queryFroObject()方法;

public <T> T queryForObject(String sql, @Nullable Object[] args, RowMapper<T> rowMapper)

 参数分别是sql,sql参数数组(可为空),对象映射关系


3,查询对象列表可以使用queryForList()或者query()方法;

public <T> List<T> queryForList(String sql, Object[] args)

参数分别是sql,sql参数数组(可为空)


public <T> List<T> query(String sql, @Nullable Object[] args, RowMapper<T> rowMapper)

参数分别是sql,sql参数数组(可为空),对象映射关系


任务一中要查询的是学员对象列表,所以使用第三种:

分别是:

query()方法:

List<Student> list = jdbcTemplate.query("select * from studentlist",new MyRowMapper());

queryForList()方法:

List list = jdbcTemplate.queryForList("select * from studentlist");
Iterator it = list.iterator();
while(it.hasNext()) {
Map rece = (Map) it.next();
    System.out.println(rece.get("Name"));
}

其中MyRowMapper是自己创建的一个RowMapper的实现类,其作用是将query等方法输出的结果集封装成我们所需要的Student对象:

package DaoImapl;

import Model.Student;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyRowMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int num)throws SQLException {

Student student = new Student();
       student.setID(rs.getLong("ID"));
       student.setName(rs.getString("Name"));
       return student;
   }

}


另外由于StudentDaoImpl实现类中每一次操作增删改查都要连接数据库,这一部分有很多重复代码,所以可以将它们进行封装成一个静态方法:

public static void JdbcUtil(){
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
   dataSource.setUrl("jdbc:mysql://localhost:3306/studentlist");
   dataSource.setUsername("root");
   dataSource.setPassword("1234");
   jdbcTemplate = new JdbcTemplate(dataSource);
}

后面只需要调用这个方法即可:

public void Insert(Student student) {
JdbcUtil();
   jdbcTemplate.update("insert into studentlist(ID,Name,QQ,Type,Time,School,Num,Link,Wish,Leader,Create_at,Update_at)values(?,?,?,?,?,?,?,?,?,?,?,?)",student.getID(),student.getName(),student.getQQ(),student.getType(),student.getTime(),student.getSchool(),student.getNum(),student.getLink(),student.getWish(),student.getLeader(),student.getCreate_at(),student.getUpdate_at());
}

public void Delete(Long ID){
JdbcUtil();
   jdbcTemplate.update("delete from studentlist where ID=?",ID);

}

public void Update(Student student){
JdbcUtil();
   jdbcTemplate.update("update studentlist set Name = ?,where ID =?",student.getName(),student.getID());
}

public Student SelectById(Long ID){
JdbcUtil();
   return jdbcTemplate.queryForObject("select * from studentlist where ID=?",new MyRowMapper(),ID);
}

public List<Student> SelectAll(){

JdbcUtil();
  // List<Student> list = jdbcTemplate.query("select * from studentlist",new MyRowMapper());
  List list = jdbcTemplate.queryForList("select * from studentlist");
   Iterator it = list.iterator();
   while(it.hasNext()) {
Map rece = (Map) it.next();
       System.out.println(rece.get("Name"));
   }
return list;
}

创建测试类:

import DaoImapl.StudentDaoImpl;
import Model.Student;
import org.junit.jupiter.api.Test;

public class JunitTest {
@Test
   public void InsertTest(){
Student s1 = new Student(0L,"张三");
       new StudentDaoImpl().Insert(s1);
   }

@Test
   public void DeleteTest(){
new StudentDaoImpl().Delete(2L);
   }

@Test
   public void UpdateTest(){
Student student = new Student(2L,"李四");
       new StudentDaoImpl().Update(student);

   }

@Test
   public void SelectByIdTest(){
System.out.println(new StudentDaoImpl().SelectById(2L));
   }

@Test
   public void SelectAllTest(){
System.out.println(new StudentDaoImpl().SelectAll());
   }

}


使用Mybatis连接数据库并对其进行增删改查:

首先配置接口的映射文件StudentDao.xml:

<!DOCTYPE mapper PUBLIC "mapper" "mybatis-3-mapper.dtd" >
<mapper namespace="com.jnshu.Dao.StudentDao">

   <!-- 插入数据,这里ID是自动递增的,所有不需要插入 -->
   <insert id="Insert" parameterType="com.jnshu.Model.Student" >
       <!-- 数据库增加语句:#{}代表占位符 -->
       insert into studentlist(ID,Name,QQ,Type,Time,School,Num,Link,Wish,Leader,Create_at,Update_at)values(#{ID},#{Name},#{QQ},#{Type},#{Time},#{School},#{Num},#{Link},#{Wish},#{Leader},#{Create_at},#{Update_at})
</insert>

   <!-- 查询表中所有的数据 -->
   <select id="SelectAll" resultType="com.jnshu.Model.Student">
       select * from studentlist
</select>

   <!-- 根据ID查询表数据 -->
   <select id="SelectById" parameterType="Long" resultType="com.jnshu.Model.Student">
       select * from studentlist where id=#{id}
</select>

   <!-- 根据ID修改表中数据-->
   <update id="Update" parameterType="com.jnshu.Model.Student">
       update studentlist set Name=#{Name} where ID=#{ID}
</update>

   <!-- 根据ID删除表数据 -->
   <delete id="Delete" parameterType="Long">
       delete from studentlist where id=#{id}
</delete>
</mapper>


然后配置Mybatis的配置文件config.xml,其作用主要是配置连接数据库的各项参数,如username,password等等,以及制定接口映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "config" "mybatis-3-config.dtd" >
<configuration>
   <!-- 别名 -->
   <typeAliases>
       <typeAlias alias="Student" type="com.jnshu.Model.Student"/>
   </typeAliases>
   <!-- 基础环境配置:包含数据源和事务管理  -->
   <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC" />
           <dataSource type="POOLED">
               <property name="driver" value="com.mysql.jdbc.Driver"/>
               <property name="url" value="jdbc:mysql://127.0.0.1:3306/studentlist" />
               <property name="username" value="root" />
               <property name="password" value="1234" />
           </dataSource>
       </environment>
   </environments>
   <!-- 映射文件配置 -->
   <mappers>
       <mapper resource="StudentDao.xml" />
   </mappers>
</configuration>


然后编写测试类:

import com.jnshu.Dao.StudentDao;
import com.jnshu.Model.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class MybatisTest {
static SqlSessionFactory factory;
   static SqlSession session;

   @Test
   public void InsertTest()throws IOException{
           MybatisUtil();
           StudentDao studentDao = session.getMapper(StudentDao.class);
           Student student = new Student(0L,"insert测试");
           studentDao.Insert(student);
           session.commit();
           System.out.println("插入数据成功");
   }

@Test
   public void DeleteTest()throws IOException{
       MybatisUtil();
       StudentDao studentDao = session.getMapper(StudentDao.class);
       studentDao.Delete(3L);
       session.commit();
       System.out.println("删除数据成功");
   }

@Test
   public void UpdateTest()throws IOException{
       MybatisUtil();
       StudentDao studentDao = session.getMapper(StudentDao.class);
       Student student = new Student(2L,"update测试");
       studentDao.Update(student);
       session.commit();
       System.out.println("修改数据成功");
   }

@Test
   public void SelectByIdTest()throws IOException{
       MybatisUtil();
       StudentDao studentDao = session.getMapper(StudentDao.class);
       Student student = studentDao.SelectById(1L);
       session.commit();
       System.out.println(student);
   }

@Test
   public void SelectAllTest()throws IOException{
       MybatisUtil();
       StudentDao studentDao = session.getMapper(StudentDao.class);
       List<Student> list = studentDao.SelectAll();
       session.commit();
       System.out.println(list);
   }
   //创建一个工具类,作用是使用Mybatis连接数据库
   public static void MybatisUtil()throws IOException{
       Reader is = Resources.getResourceAsReader("config.xml");
       factory = new SqlSessionFactoryBuilder().build(is);
       session = factory.openSession();
   }
}

这里我还是编写了一个静态方法来使用Mybatis连接数据库,精简代码,不然增删改查每个方法都要写一遍连接过程,显得很冗长。

可以看出相比于JDBCTemplate,Mybatis显得简便了许多,由于使用了动态代理,Mybatis不需要编写接口对应的实现类,只需要编写接口映射文件。


然后是Spring的学习:

spring主要是要配置applicationContext.xml,这里我使用的是注解注入:

<?xml version = "1.0" encoding = "utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context.xsd">
<!--
   注解扫描
   扫描spring包中的注解
-->
<context:component-scan base-package="com.jnshu.Impl"></context:component-scan>


<!--配置数据源-->
<bean id="dataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
   <property name="url" value="jdbc:mysql://localhost/studentlist"/>
   <property name="username" value="root"/>
   <property name="password" value="1234"/>
</bean>
<!--创建JdbcTemplate对象 注入dataSource-->
<bean id="jdbcTemplate"
     class="org.springframework.jdbc.core.JdbcTemplate">
   <property name="dataSource" ref="dataSource"/>
</bean>
</beans>


创建接口实现类StudentDaoImpl:

package com.jnshu.Impl;

import com.jnshu.Model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StudentDaoImpl {

@Autowired
   private JdbcTemplate jdbcTemplate;

   public void Insert(Student student){
        String sql ="insert into studentlist(ID,Name,QQ,Type,Time,School,Num,Link,Wish,Leader,Create_at,Update_at)values(?,?,?,?,?,?,?,?,?,?,?,?)";
       jdbcTemplate.update(sql,student.getID(),student.getName(),student.getQQ(),student.getType(),student.getTime(),student.getSchool(),student.getNum(),student.getLink(),student.getWish(),student.getLeader(),student.getCreate_at(),student.getUpdate_at());
   }

public void Delete(Long ID){
       String sql ="delete from studentlist where ID=?";
       jdbcTemplate.update(sql,ID);
   }

public void Update(Student student){
       String sql ="update studentlist set Name = ?where ID =?";
       jdbcTemplate.update(sql,student.getName(),student.getID());
   }

public Student SelectById(Long ID){
       String sql ="select * from studentlist where ID=?";
       return jdbcTemplate.queryForObject(sql,new MyRowMapper(),ID);
   }

public List<Student> SelectAll(){
       String sql ="select * from studentlist";
       return jdbcTemplate.query("select * from studentlist",new MyRowMapper());
   }

}


创建测试类:

import com.jnshu.Impl.StudentDaoImpl;
import com.jnshu.Model.Student;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

private ApplicationContext ac;

   @BeforeEach
   public void into(){
       ac = new ClassPathXmlApplicationContext("applicationContext.xml");
   }

@Test
   public void InsertTest(){
       StudentDaoImpl studentDaoImpl = (StudentDaoImpl) ac.getBean("studentDaoImpl");
       studentDaoImpl.Insert(new Student(0L,"springInsert"));
   }

@Test
   public void DeleteTest(){
       StudentDaoImpl studentDaoImpl = (StudentDaoImpl) ac.getBean("studentDaoImpl");
       studentDaoImpl.Delete(10L);
   }

@Test
   public void UpdateTest(){
       StudentDaoImpl studentDaoImpl = (StudentDaoImpl) ac.getBean("studentDaoImpl");
       studentDaoImpl.Update(new Student(10L,"springUpdate"));
   }

@Test
   public void SelectByIdTest(){
       StudentDaoImpl studentDaoImpl = (StudentDaoImpl) ac.getBean("studentDaoImpl");
       System.out.println(studentDaoImpl.SelectById(1L));
   }

@Test
   public void SelectAllTest(){
       StudentDaoImpl studentDaoImpl = (StudentDaoImpl) ac.getBean("studentDaoImpl");
       System.out.println(studentDaoImpl.SelectAll());
   }
}


可以发现使用spring之后不需要我们手动创建实现类对象了,全部交由spring来替我们创建。


返回列表 返回列表
评论

    分享到