mybatis开发dao方法有两种:
1、mapper代理方法(程序员只需要写mapper接口(相当于dao接口))
2、原始dao开发方法(程序员需要写dao接口和dao实现类)
先从原始入手,介绍原始dao开发方法
使用原始方法开发dao
pom.xml加载mysql、mybatis、junit驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
文件总览:
og4j.properties
配置日志信息
# Global logging configuration
#在开发环境下日志级别要设置成DEBUG,生产环境设置成info或error
log4j.rootLogger=DEBUG,stdout
#Console output...
#把日志信息输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#设置使用灵活布局
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#定义输出格式
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
jdbc.properties
用来存放配置信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
SqlMapConfig.xml
数据库连接信息以及自定义sql文件(mapper.xml,我这里是User.xml)的引用
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!--加载映射文件
-->
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
</configuration>
User.xml(mapper.xml)
映射文件。定义sql语句
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<!--namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用
在映射文件中使用paramterType指定输入的类型
在映射文件中使用resultType指定输出的类型
-->
<!--#{}表示一个占位符号-->
<select id="findUserById" parameterType="int" resultType="com.day1.pojo.User">
select * from users where id=#{id}
</select>
<!-- 模糊查询 ,可能反回多条数据
使用${}拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。注意,使用${}可能会引起sql注入
${value}:接收输入参数的内容。如果传入的类型是简单类型,那么${}中只能使用value
-->
<select id="findUserByName" parameterType="java.lang.String" resultType="com.day1.pojo.User">
<!--select * from users where username like #{value}-->
select * from users where username like '%${value}%'
</select>
<!--添加用户
parametetType指定参数类型是pojo(包括用户信息)
#{}中指定pojo的属性名,接收到pojo属性值
如果id自增则不用设置id,系统自动生成id。
insert into users(id,username,password) value (#{id},#{username},#{password})
-->
<insert id="insertUser" parameterType="com.day1.pojo.User">
<!--将插入数据的主键返回,返回到User对象中
select last_insert_id()得到insertj进去的主键值,只适用于自增主键
keyproperty:将查询到主键设置到parameterType指定的对象的哪个属性
order:相对于insert语句的来说的执行顺序
-->
<selectKey order="AFTER" keyProperty="id" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into users(username,password) value (#{username},#{password})
</insert>
<!--根据id删除用户-->
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>
<!--更新用户
需要传入id和用户更新信息
#{id}:从输入user对象中获取id值
-->
<update id="updateUser" parameterType="com.day1.pojo.User">
update users set username=#{username},password=#{password} where id=#{id}
</update>
</mapper>
pojo.User
定义实体类,属性对应数据库。
package com.day1.pojo;
public class User {
private int id;
private String username;
private String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword(String erlengzi) {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
dao接口
package com.day1.dao;
import com.day1.pojo.User;
public interface UserDao {
//根据id查询用户信息
public User findUserById(int id) throws Exception;
//添加用户信息
public void insertUser(User user)throws Exception;
//删除用户信息
public void deleteUser(int id)throws Exception;
}
dao实现类
package com.day1.dao;
import com.day1.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
public class UserDaoImpl implements UserDao {
/*需要将dao实现类中注入SqlSessionFactory
这里通过构造方法注入*/
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.findUserById",id);
//释放资源
sqlSession.close();
return user;
}
@Override
public void insertUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行插入的操作
sqlSession.insert("test.inserUser",user);
//提交
sqlSession.commit();
//关闭资源
sqlSession.close();
}
@Override
public void deleteUser(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行插入的操作
sqlSession.delete("test.deleteUser",id);
//提交
sqlSession.commit();
//关闭资源
sqlSession.close();
}
}
测试类
package com.day1.test;
import com.day1.dao.UserDao;
import com.day1.dao.UserDaoImpl;
import com.day1.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
public class UserDaoImplTest {
private SqlSessionFactory sqlSessionFactory;
//此方法是在testFindUserById()之前执行的
@Before
public void setUp() throws Exception{
//创建sqlSessionFactory
//mabatis配置文件
String resource = "SqlMapConfig.xml";
//得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂.传入mybatis的配置文件信息
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById() throws Exception {
//创建Ueser的对象
UserDao userdao = new UserDaoImpl(sqlSessionFactory);
//调用UserDao方法
User user = userdao.findUserById(1);
System.out.println(user);
}
}
总结开发问题
1、dao接口实现类中存在大量的模板方法(重复代码)
2、调用sqlsession方法时将statement的id硬编码了
3、调用sqlsession方法时传入的变量,由于sqlsession方法使用泛型,即使变量传入错误,编译时也不报错。