项目结构:
mybatis.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="db.properties" />
<typeAliases>
<package name="com.guo.bean"/><!-- 默认类名简写 -->
</typeAliases>
<!--环境配置,连接的数据库-->
<environments default="mysql"><!-- 默认是mysql -->
<environment id="mysql">
<transactionManager type="JDBC"/><!--指定事务管理的类型,这里简单使用Java的JDBC的提交和回滚设置 -->
<dataSource type="POOLED"><!--dataSource 指连接源配置,POOLED是JDBC连接对象的数据源连接池的实现 -->
<property name="driver" value="${mysql.driver}"></property>
<property name="url" value="${mysql.url}"></property>
<property name="username" value="${mysql.username}"></property>
<property name="password" value="${mysql.password}"></property>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.guo.dao"/> <!--加载com/guo/dao下的配置文件-->
</mappers>
</configuration>
MyBatisUtil工具类:
public class MyBatisUtil {
private final static ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();
private static SqlSessionFactory getSqlSessionFactory() {
SqlSessionFactory ssf = null;
try(InputStream is = Resources.getResourceAsStream("mybatis.xml");) {
ssf = new SqlSessionFactoryBuilder().build(is);
}catch(Exception e) {
e.printStackTrace();
return null;
}
return ssf;
}
public static SqlSession getSession() {
SqlSession session = local.get();
if(session == null) {
session = getSqlSessionFactory().openSession();
local.set(session);
}
return session;
}
}
实体类与数据库表
PersonDao接口和PersonDao.xml(两个文件名必须相同)
<select id="findByID" parameterType="java.lang.Integer" resultMap="Person">
select * from person join address on person.address = address.id where person.id = #{id}
</select>
<insert id="add" parameterType="Person">
insert into person(name,gender,age,address) values(#{name},#{gender},#{age},#{address.id})
</insert>
一对一映射配置(以人与地址为例)
1、级联式
2、引用关联式
3、内部属性关联式
4、终极级联查询模式
接口com.guo.dao.AddressDao
public interface AddressDao {
Address findByID(Integer id);// 配置级联查询的方法
}
AddressDao.xml
<?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.guo.dao.AddressDao">
<resultMap type="Address" id="Address">
<id property="id" column="ID" />
<result property="province" column="PROVINCE" />
<result property="city" column="CITY" />
<result property="area" column="AREA" />
</resultMap>
<select id="findByID" parameterType="java.lang.Integer" resultType="Address">
select * from address where id=#{id}
</select>
</mapper>
测试:
public class TestMyBatis {
private SqlSession session;
private PersonDao personDao;
@Before
public void before() {
session = MyBatisUtil.getSession();
personDao = session.getMapper(PersonDao.class);
}
@Test
public void test() {
System.out.println(personDao.findByID(1));
}
@After
public void after() {
session.commit();
session.close();
}
}
一对多映射配置(以部门与员工为例)
实体类与数据库表
EmployeeDao接口与Employee.xml
public interface EmployeeDao {
void add(Map<String, Object> map) ;
Set<Employee> findByDeptno(Integer deptno);
}
<?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.guo.dao.EmployeeDao">
<resultMap type="Employee" id="Employee">
<id property="workID" column="WORKID" />
<result property="name" column="NAME" />
<result property="hireDate" column="HIREDATE" javaType="java.util.Date" jdbcType="DATE"/><!--DATE 一定要大写 -->
</resultMap>
<select id="selectAll" resultMap="Employee">
select * from emp join dept on emp.deptno = dept.no
</select>
<insert id="add" parameterType="java.util.Map">
insert into emp(name,hiredate,deptno)
values(#{emp.name},#{emp.hireDate},#{dept.no})
</insert>
<select id="findByDeptno" parameterType="java.lang.Integer" resultMap="Employee">
select * from emp where deptno=#{deptno}
</select>
</mapper>
DeptDao接口与DeptDao.xml
测试:
public class TestMyBatis {
private SqlSession session;
private DeptDao deptDao;
private EmployeeDao employeeDao;
@Before
public void before() {
session = MyBatisUtil.getSession();
personDao = session.getMapper(PersonDao.class);
deptDao = session.getMapper(DeptDao.class);
employeeDao = session.getMapper(EmployeeDao.class);
}
@Test
public void test() {
try {
Dept d = deptDao.findByNO(1);//查询部门
employeeDao.findByDeptno(1);//部门1下的员工集合
Employee e = new Employee(null,"安爱虎", new Date());
Map<String, Object> map = new HashMap<>();
map.put("emp", e);
map.put("dept",d);
employeeDao.add(map);
} catch (Exception e) {
e.printStackTrace();
}
}
@After
public void after() {
session.commit();
session.close();
}
}
另外
还可以在Employee类中添加Dept属性,如下:
public class Employee {
private Integer workID;
private String name;
private Date hireDate;
private Dept dept;
// 省略get、set方法
@Override
public String toString() {
return "Employee [workID=" + workID + ", name=" + name + ", hireDate=" + hireDate + ", dept=" + dept + "]";
}
}
在EmployeeDao.xml添加如下配置(红色框):
这样一来,写查询语句就不用连接了,直接查询:select * from emp