导读
注解开发的方式只需要程序员开发Mapper接口即可,不需要编写映射文件(XML)。
环境搭建
项目结构
SqlMapConfig.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 引入外部配置文件 --> <properties resource="db.properties"></properties> <!-- 数据库链接相关 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </dataSource> </environment> </environments> <mappers> <!-- 添加单个接口 --> <!-- <mapper class="com.cyb.anno.AnnotationDeptMapper" /> --> <!-- 批量添加 --> <package name="com.cyb.anno"/> </mappers> </configuration>
db.properties
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/cyb
db.username=root
db.password=root
Dept.java
package com.cyb.po; public class Dept { private int id; private String name; private int sex; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } @Override public String toString() { return "Dept [id=" + id + ", name=" + name + ", sex=" + sex + "]"; } }
AnnotationDeptMapper.java(接口)
package com.cyb.anno; import java.util.List; import org.apache.ibatis.annotations.Select; import com.cyb.po.Dept; public interface AnnotationDeptMapper { @Select("SELECT * FROM dept WHERE id = #{id}") public Dept findDeptById(int id); @Select("SELECT * FROM dept where name like '%${value}%'") public List<Dept> findDeptList(String name); }
TestDept.java
package com.cyb.test; import java.io.InputStream; import java.util.List; 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.Before; import org.junit.Test; import com.cyb.anno.AnnotationDeptMapper; import com.cyb.po.Dept; public class TestDept { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws Exception { //指定全局配置文件路径 String resource = "SqlMapConfig.xml"; //加载资源文件(包括全局文件和映射文件) InputStream inputStream = Resources.getResourceAsStream(resource); //使用构建者模式创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testSelect() { //由SqlSessionFactory工厂去创建SqlSession(会话) SqlSession sqlSession = sqlSessionFactory.openSession(); AnnotationDeptMapper deptMapper = sqlSession.getMapper(AnnotationDeptMapper.class); List<Dept> dept=deptMapper.findDeptList("al"); System.out.println(dept.size()); //释放资源 sqlSession.close(); } }