<configuration>
<properties resource="jdbcConfig.properties">
</properties>
<settings>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--Mybatis每个属性都会按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<mapper namespace="com.itcast.dao.IAccountDao">
<!--定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--应当建立一对一的关系映射:配置封装user的内容-->
<!--
使用association标签配置延迟加载
通过select属性指定的唯一内容,查询用户的唯一标识-根据id查询用户的配置
column属性指定的内容:用户根据id查询时,所需要参数的值
-->
<association property="user" column="uid" javaType="user" select="com.itcast.dao.IUserDao.findById">
</association>
</resultMap>
<select id="findAll" resultMap="accountUserMap" >
SELECT * FROM account
</select>
</mapper>
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{uid}
</select>
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
/*for (Account account : accounts) {
System.out.println("-----每个account的信息-----");
System.out.println(account);
System.out.println(account.getUser());*/
}
<mapper namespace="com.itcast.dao.IAccountDao">
<!--定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--应当建立一对一的关系映射:配置封装user的内容-->
<!--
使用association标签配置延迟加载
通过select属性指定的唯一内容,查询用户的唯一标识-根据id查询用户的配置
column属性指定的内容:用户根据id查询时,所需要参数的值
-->
<association property="user" column="uid" javaType="user" select="com.itcast.dao.IUserDao.findById"></association>
<collection property="accounts" ofType="account" select="com.itcast.dao.IUserDao.findAccountByUid" column="id"></collection>
</resultMap>
<!--根据用户id查询账户列表-->
<select id="findAccountByUid" resultType="account">
SELECT * FROM account where uid = #{uid}
</select>
</mapper>
<mapper namespace="com.itcast.dao.IUserDao">
<!--定义user的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!--配置user对象中account集合的映射-->
<collection property="accounts" ofType="account">
</collection>
</resultMap>
<select id="findAll" resultMap="userAccountMap" >
SELECT * FROM USER
</select>
</mapper>
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
/*for (User user : users) {
System.out.println("-----每个account的信息-----");
System.out.println(user);
System.out.println(user.getAccounts());
}*/
}
<?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.itcast.dao.IUserDao">
<select id="findAll" resultType="user">
SELECT * FROM USER
</select>
<select id="findById" parameterType="int" resultType="user">
SELECT * FROM USER where id = #{uid}
</select>
</mapper>
/**
* session关闭,缓存消失
*/
@Test
public void testFirstLevelCache(){
User user1 = userDao.findById(41);
System.out.println(user1);
//关闭sesson
/*sqlSession.close();
sqlSession = factory.openSession();
userDao = sqlSession.getMapper(IUserDao.class);*/
//SQLSession清空缓存的方法,也可以清空缓存,执行两次查询
sqlSession.clearCache();
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1==user2);
}
<!--更新用户信息-->
<update id="updateUser" parameterType="user">
update user set username=#{username},address=#{address} where id =#{id}
</update>
/**
* 测试缓存的同步
*/
@Test
public void testClearCache(){
//1.根据id查询用户
User user1 = userDao.findById(41);
System.out.println(user1);
//2.更新用户信息
user1.setUsername("clear cache");
user1.setAddress("望京");
//userDao.updateUser(user1);
//3.再次查询id为41的用户
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user1==user2);
}
/**
* session关闭,缓存消失
*/
@Test
public void testFirstLevelCache(){
SqlSession sqlSession1 = factory.openSession();
IUserDao dao1 = sqlSession1.getMapper(IUserDao.class);
User user1 = dao1.findById(41);
System.out.println(user1);
sqlSession1.close();//一级缓存消失
SqlSession sqlSession2 = factory.openSession();
IUserDao dao2 = sqlSession2.getMapper(IUserDao.class);
User user2 = dao2.findById(41);
System.out.println(user2);
sqlSession2.close();
System.out.println(user1==user2);
}
//结果不可以
<configuration>
<properties resource="jdbcConfig.properties">
</properties>
<settings>
<setting name="cacheEnabled" value="true"/>
<!--默认为true-->
</settings>
<mapper namespace="com.itcast.dao.IUserDao">
<!--开启user支持二级缓存-->
<select id="findAll" resultType="user" useCache="true">
SELECT * FROM USER
</select>
<?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="jdbcConfig.properties"></properties>
<!-- 配置别名 -->
<typeAliases>
<package name="com.itheima.domain"></package>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<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>
<!-- 指定带有注解的dao接口所在位置 -->
<mappers>
<package name="com.itheima.dao"></package>
</mappers>
</configuration>
package com.itheima.dao;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 在Mybatis中,针对CRUD共有4个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
}
package com.itheima.test;
import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
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.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisAnnoTest {
/**
* 测试基于注解的Mybatis使用
* @param args
*/
public static void main(String[] args) throws IOException {
//1.获取字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据字节输入流获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.根据SqlSessionFactory生产一个SqlSession
SqlSession session = factory.openSession();
//4.使用SqlSession获取Dao的代理对象
IUserDao userDao = session.getMapper(IUserDao.class);
//5.执行Dao的方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
//6.释放资源
session.close();
in.close();
}
}
<!-- 指定带有注解的dao接口所在位置 -->
<mappers>
<!--<package name="com.itheima.dao"></package>-->
<!--也不可以<mapper class="com.itheima.dao.IUserDao"></mapper>-->
<!--使用xml配置<mapper resource="com/itheima/dao/IUserDao.xml"></mapper>-->
</mappers>
package com.itheima.dao;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 在Mybatis中,针对CRUD共有4个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id = #{id}")
void deleteUser(Integer userId);
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id = #{id}")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
//@Select("select * from user where username like #{username}")---字符串拼接
//模糊查询的另外一种写法,固定属性名称value---参数占位符
@Select("select * from user where username like ‘%${value}%‘")
List<User> findByName(String username);
/**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user")
int findTotal();
}
package com.itheima.test;
import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class AnnotationCRUDTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
private SqlSessionFactory factory;
/**
* 在测试方法执行之前执行
* @throws IOException
*/
@Before
public void init() throws IOException {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂对象,创建dao对象
//userDao = new UserDaoImpl(factory);
sqlSession = factory.openSession();
//4.获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
/**
* 释放资源
* 在测试方法之后执行
*/
@After
public void destroy() throws IOException {
//提交事务
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void testDelete(){
/*User user = new User();
user.setId(52);*/
userDao.deleteUser(52);
}
@Test
public void testFindOne(){
User user = userDao.findById(53);
System.out.println(user);
}
@Test
public void testFindByName(){
//List<User> users = userDao.findByName("%王%");
List<User> users = userDao.findByName("王");
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testFindTotal(){
int total = userDao.findTotal();
System.out.println(total);
}
}
package com.itheima.dao;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* 在Mybatis中,针对CRUD共有4个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
})
List<User> findAll();
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id = #{id}")
@ResultMap(value="userMap")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
//@Select("select * from user where username like #{username}")---字符串拼接
//模糊查询的另外一种写法,固定属性名称value---参数占位符
@Select("select * from user where username like ‘%${value}%‘")
@ResultMap("userMap")
List<User> findByName(String username);
}
package com.itheima.dao;
import com.itheima.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IAccountDao {
/**
* 查询所有账户,并且获取每个账户的用户信息
* @return
*/
@Select("select * from account")
@Results(id = "accountMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
@Result(property = "user",column = "uid",one=@One(select="com.itheima.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();
}
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//多对一(Mybatis中称为一对一的映射):一个账户只能属于一个用户
//一个用户对应多个账户,一个账户只属于一个用户
private User user;
public User getUser() {
return user;
}
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts",column = "id",
many=@Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll();
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println("---每个用户的信息:---");
System.out.println(user);
//实现了延迟加载,没有立即查询account
//System.out.println(user.getAccounts());
}
}
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
//包含一对多关系映射:一个用户对应多个账户
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
package com.itheima.test;
import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class AnnotationCRUDTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
private SqlSessionFactory factory;
/**
* 在测试方法执行之前执行
* @throws IOException
*/
@Before
public void init() throws IOException {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.使用工厂对象,创建dao对象
//userDao = new UserDaoImpl(factory);
sqlSession = factory.openSession();
//4.获取dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
/**
* 释放资源
* 在测试方法之后执行
*/
@After
public void destroy() throws IOException {
//提交事务
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println("---每个用户的信息:---");
System.out.println(user);
//实现了延迟加载,没有立即查询account
//System.out.println(user.getAccounts());
}
}
@Test
public void testFindOne(){
User user = userDao.findById(41);
System.out.println(user);
User user2 = userDao.findById(41);
System.out.println(user2);
System.out.println(user==user2);
}
@Test
public void testFindByName(){
//List<User> users = userDao.findByName("%王%");
List<User> users = userDao.findByName("王");
for (User user : users) {
System.out.println(user);
}
}
}
<configuration>
<!-- 引入外部配置文件 -->
<properties resource="jdbcConfig.properties"></properties>
<!--全局配置:开启二级缓存(默认开启)-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
@CacheNamespace(blocking = true)
public interface IUserDao {
原文:https://www.cnblogs.com/liujinhui/p/380aa39d265f8ebf69a7878dd53afe8e.html