MyBatis框架学习
xml配置的工程目录结构
jdbcConfig.properties
用于配置数据库的连接信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=tmd928865598..
SqlMapConfig.xml
mybatis工程的主配置文件
<?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="jdbcConfig.properties"></properties>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="jdbc"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的4个基本信息-->
<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>
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="com/itheima/dao/IUserDao.xml"/>
</mappers>
</configuration>
IUserDao.xml
配置IUserDao的具体实现,在resouses包下应该与IuserDao类目录一致
例如IuserDao.xml与IUserDao类的目录均为com.itheima.dao
下面展示基本查询:
使用select标签
<?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.itheima.dao.IUserDao">
<!-- 查询所有 -->
<!--
id为IuserDao下的方法名
resultType为该方法的返回类
parameterType为参数
-->
<select id="findAll" resultType="com.itheima.domain.User">
select * from user;
</select>
<!-- 根据id查询用户 -->
<select id="findUserById" parameterType="INT" resultMap="com.itheima.domain.User">
select * from user where id = #{uid}
</select>
</mapper>
- select 查询标签
- insert 保存标签
- update 更新标签
- delete 删除标签
保存用户,并获取其Id
<insert id="saveUser" parameterType="com.itheima.domain.User">
<!-- 配置插入操作后,获取插入数据的id -->
<selectKey keyProperty="userId" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)values(#{userName},#{userAddress},#{userSex},#{userBirthday});
</insert>
@Test
public void testSave(){
User user = new User();
user.setUserAddress("北京市朝阳区");
user.setUserSex("男");
user.setUserBirthday(new Date());
user.setUserName("mybatistest");
System.out.println("-------------------保存前-------------------");
System.out.println(user);
userDao.saveUser(user);
System.out.println("-------------------保存后-------------------");
System.out.println(user);
}
当数据库表的列名与与定义的实体类的变量名不一致时
例如数据库中为
实体类中为
需要配置查询结果的列名与实体类的属性名的对应关系
<resultMap id="userMap" type="com.itheima.domain.User">
<!-- 主键字段的对应 -->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<!--property为实体类中的属性名,column为数据库表中的列名-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
</resultMap>
此时需要返回该实体类的方法需要稍作更改,例如查询方法需要将resultType---->resultMap
<!-- 查询所有 -->
<select id="findAll" resultMap="userMap">
select * from user;
</select>
具体使用
private InputStream in;
private SqlSession session;
private IUserDao userDao;
@Before
public void init(){
try {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
session = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
userDao = session.getMapper(IUserDao.class);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void destory(){
try {
session.commit();
session.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (int i = 0; i < users.size(); i++) {
System.out.println(users.get(i));
}
}
一对一/多映射查询(方法一)立即加载
添加这三个文件,假设一个用户有多个账户,一个账户有一个用户
Account中的属性应为
IAccountDao.xml
配置resultMap
<resultMap id="accountUserMap" type="com.itheima.domain.Account">
<id property="id" column="aid"></id>
<result property="uId" column="uid"></result>
<result property="money" column="money"></result>
<!--一对一的关系映射:配置封装user的内容-->
<association property="user" column="uid" javaType="com.itheima.domain.User">
<!-- 主键字段的对应 -->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
</association>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="accountUserMap">
select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id = a.uid;
</select>
IUserDao.xml
配置之前需要在User实体类中添加
然后配置.xml文件
<resultMap id="userAccountMap" type="com.itheima.domain.User">
<!-- 主键字段的对应 -->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
<!--配置user对象中accounts集合的映射-->
<collection property="accountList" ofType="com.itheima.domain.Account">
<id property="id" column="aid"></id>
<result property="uId" column="uid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="userAccountMap">
select * from user u left outer join account a on u.id = a.uid
</select>
一对一/多映射查询(方法二)可延迟加载
在SqlMapConfig.xml文件中可配置settings时,延迟加载
1. 一对一
配置IAccountDao.xml文件中的association标签,在IUserDao.xml中配置findById方法
<association property="user" column="uid" javaType="com.itheima.domain.User"
select="com.itheima.dao.IUserDao.findById"></association>
<!-- 根据id查询用户 -->
<select id="findUserById" parameterType="INT" resultMap="userMap">
select * from user where id = #{uid}
</select>
2. 一对多
配置IUserDao.xml文件中的collection标签,在IAccountDao.xml文件中配置findAccountByUid方法
<!--配置user对象中accounts集合的映射-->
<collection property="accountList" ofType="com.itheima.domain.Account"
select="com.itheima.dao.IAccountDao.findAccountByUid" column="id">
</collection>
<select id="findAccountByUid" parameterType="java.lang.Integer" resultType="com.itheima.domain.Account">
select * from account where uid = #{id}
</select>
注解配置
在SqlMapConfig.xml文件中更改mappers标签内容
<mapper class="com.itheima.dao.IUserDao"></mapper>
<mapper class="com.itheima.dao.IAccountDao"></mapper>
或者直接改成
<package name="com.itheima.dao"></package>
注解直接在dao包下对每个方法配置
例如IUserDao
//开启缓存
@CacheNamespace(blocking = true)
public interface IUserDao {
/**
* 查询所有
* @return
*/
@Select("select * from user")
@Results(id ="userMap",value = {
@Result(id = true,property = "userId",column = "id"),
@Result(property = "userName",column = "username"),
@Result(property = "userAddress",column = "address"),
@Result(property = "userSex",column = "sex"),
@Result(property = "userBirthday",column = "birthday"),
@Result(property = "accounts",column = "id",
many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
@Select("select * from user where id=#{id}")
@ResultMap(value = "userMap")
User findById(Integer id);
@Select("select * from user where username like #{username}")
@ResultMap(value = "userMap")
List<User> findByName(String userName);
}
在IAccountDao中
public interface IAccountDao {
/**
*查询所有账户,并获取每个账户的所属用户信息
* @return
*/
@Select("select * from account")
@Results(id = "accountMap",value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "uid",column = "uid"),
@Result(property = "money",column = "money"),
@Result(property = "user",column = "uid",
one = @One(select = "com.itheima.dao.IUserDao.findById",
fetchType = FetchType.EAGER))
})
List<Account> findAll();
@Select("select * from account where uid = #{id}")
List<Account> findAccountByUid(int id);
}