接口代理方式实现Dao层开发
我们在实现的开发过程中都是写接口的
文章目录
前言
采用MyBatis的基于接口代理方式实现持久层的开发,这种方法是我们在企业中使用的主流。基于接口代理方式的开发只需要实现程序员实现Mapper接口,MyBatis框架会为我们动态的生成实现类的对象
提示:以下是本篇文章正文内容,下面案例可供参考
一、必须遵守的规范
1.Mapper.xml映射文件中的namespace属性值与Mapper接口的全限名一致
2.Mapper接口中方法名和Mapper.xml映射文件中的定义的每个statement的id值要一致
3.Mapper映射文件中的parameterType的值一定是接口中方法的参数
在没有指定别名的条件下都要使用完全限定名!!!
二、开发步骤
1.引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.offcn</groupId>
<artifactId>MyBatis03</artifactId>
<version>1.0</version>
<!--引入依赖-->
<dependencies>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- MyBatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- 引入测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--引入日志文件-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
<!--可以让xml文件进行编译-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
2.核心配置文件的编写
该配置文件一般称作SqlMapConfig放在main下的resources文件中
<?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">
<!--MyBatis核心配置文件-->
<configuration>
<properties resource="db.properties"></properties>
<!--简化返回值类型和传入值的类型-->
<typeAliases>
<package name="com.offcn.entity"/>
</typeAliases>
<!--环境配置-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<!--type="POOLED"表示显示连接池的数据源-->
<dataSource type="POOLED">
<!--配置连接池-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--如果接口与接口的映射的文件在同一个包下并且他们的名字相同-->
<package name="com.offcn.mapper"/>
</mappers>
</configuration>
注意:①此时我们的别名采用的是扫描包的方式,因此我们我们的别名默认就是实体类的类名
②映射文件也是采用的扫描包的形式就必须遵守接口名和映射文件文件名一致,并且在同一个包下
3.创建数据表
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
4.实体类编写
既然要建立orm一一对应关系,就需要实体类public class Person {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
5.工具类的编写
工具类的编写也是非常有意义的可以简化我们很多代码!public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try{
//加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSeesionFactory工厂对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}catch (Exception e){
}
}
//获取SqlSession对象
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
//关闭资源
public static void closeSqlSession(SqlSession s){
s.close();
}
}
工具类的编写规范写法:
package cn.offcn.utils;
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 java.io.InputStream;
public class MyBatisUtils {
private MyBatisUtils(){}
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
private static SqlSessionFactory sqlSessionFactory = null;
static{
try{
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
resourceAsStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
private static void openSqlSession(){
SqlSession sqlSession = sqlSessionFactory.openSession();
threadLocal.set(sqlSession);
};
public static SqlSession getSqlSession(){
SqlSession sqlSession = threadLocal.get();
if(sqlSession == null){
openSqlSession();
sqlSession = threadLocal.get();
}
return sqlSession;
}
public static void close(){
SqlSession sqlSession = threadLocal.get();
if(sqlSession != null){
sqlSession.close();
threadLocal.set(null);
}
}
}
6.编写PersonMapper接口
public interface PersonMapper {
//定义一个方法用来查询所有的Person
public List<Person> getPersons();
//定义一个方法用来根据personID来查询Person
public Person getPersonById(Integer id);
//根据Person中的id删除Person
public void delePersonById(Integer id);
//添加Person
public void addPerson(Person person);
//根据Id修改Person信息
public void updatePersonById(Person person);
}
7.编写PersonMapper接口对应的映射文件
问题1:
开发者者是如何调用xml文件中的各种操作去执行sql的?
这时我们就需要用到上述的Mapper接口了,通过Mapper接口与xml建立映射关系,我们就可以通过调用Mapper接口中的方法去间接调用xml文件中相关的操作。xml文件的mapper标签中有一个属性名字叫nameapace它的值是接口的全限名,这样就可以保证接口可以找到该xml文件了。那么它又是怎么通过方法找到对应的sql呢,每个标签中会有一个属性id它与接口中的方法名一一对应。
namespace=接口的全限名
id=接口中的方法名
注意事项:映射文件名和接口名保持一致(上述配置缘故)
<?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="com.offcn.mapper.PersonMapper">
<select id="getPersons" resultType="Person">
select * from person
</select>
<select id="getPersonById" resultType="Person">
select * from person where id=#{id}
</select>
<delete id="delePersonById">
delete from person where id=#{id}
</delete>
<insert id="addPerson">
insert into person (name,age) values (#{name},#{age});
</insert>
<update id="updatePersonById">
update person set name=#{name},age=#{age} where id=#{id}
</update>
</mapper>
8.测试
注意:SqlSession默认是开启事务的,因此在做DML操作时记得提交事务哦!!!
public class PersonTest {
@Test
public void getPersons() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
List<Person> persons = mapper.getPersons();
for (Person person : persons) {
System.out.println(person);
}
MyBatisUtils.closeSqlSession(sqlSession);
}
@Test
public void getPersonByTd() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person person = mapper.getPersonById(3);
System.out.println(person);
MyBatisUtils.closeSqlSession(sqlSession);
}
@Test
public void deletPersonById() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
mapper.delePersonById(3);
sqlSession.commit();
MyBatisUtils.closeSqlSession(sqlSession);
}
@Test
public void addPerson() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person();
person.setName("大王");
person.setAge(33);
mapper.addPerson(person);
sqlSession.commit();
MyBatisUtils.closeSqlSession(sqlSession);
}
@Test
public void updatePerson() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person();
person.setName("小王");
person.setAge(22);
person.setId(5);
mapper.updatePersonById(person);
sqlSession.commit();
MyBatisUtils.closeSqlSession(sqlSession);
}
}
总结
这是基于接口代理的方式进行开发的常规步骤,后续我们可以使用注解,插件等一些操作来简化开发步骤。