赞
踩
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
/** * * <p>Title: User</p> * <p>Description: 用户的实体类</p> * <p>Company: http://www.itheima.com/ </p> */ public class User implements Serializable { private Integer userId; private String userName; private Date userBirthday; private String userSex; private String userAddress; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + ", userBirthday="+ userBirthday + ", userSex="+ userSex + ", userAddress=" + userAddress + "]"; } }
/** * * <p>Title: IUserDao</p> * <p>Description: 用户的持久层接口</p> * <p>Company: http://www.itheima.com/ </p> */ 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="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday") }) List<User> findAll(); /** * 根据 id 查询一个用户 * @param userId * @return */ @Select("select * from user where id = #{uid} ") @ResultMap("userMap") User findById(Integer userId); /** * 保存操作 * @param user * @return */ @Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})") @SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before = false, statement = { "select last_insert_id()" }) int saveUser(User user); /** * 更新操作 * @param user * @return */ @Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ") int updateUser(User user); /** * 删除用户 * @param userId * @return */ @Delete("delete from user where id = #{uid} ") int deleteUser(Integer userId); /** * 查询使用聚合函数 * @return */ @Select("select count(*) from user ") int findTotal(); /** * 模糊查询 * @param name * @return */ @Select("select * from user where username like #{username} ") List<User> findByName(String name); } 通过注解方式,我们就不需要再去编写 UserDao.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 文件的位置 --> <properties resource="jdbcConfig.properties"></properties> <!-- 配置别名的注册 --> <typeAliases> <package name="com.itheima.domain"/></typeAliases> <!-- 配置环境 --> <environments default="mysql"> <!-- 配置 mysql 的环境 --> <environment id="mysql"> <!-- 配置事务的类型是 JDBC --> <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> <!-- 配置映射信息 --> <mappers> <!-- 配置 dao 接口的位置,它有两种方式 第一种:使用 mapper 标签配置 class 属性 第二种:使用 package 标签,直接指定 dao 接口所在的包--> <package name="com.itheima.dao"/> </mappers> </configuration>
/** * * <p>Title: MybatisAnnotationCRUDTest</p> * <p>Description: mybatis 的注解 crud 测试</p> * <p>Company: http://www.itheima.com/ </p> */ public class MybatisAnnotationCRUDTest { /** * 测试查询所有 */ @Test public void testFindAll() { List<User> users = userDao.findAll(); for(User user : users) { System.out.println(user); } } /** * 测试查询一个 */ @Test public void testFindById() { User user = userDao.findById(41); System.out.println(user); } /** * 测试保存 */ @Test public void testSave() { User user = new User(); user.setUserName("mybatis annotation"); user.setUserSex("男"); user.setUserAddress("北京市顺义区"); user.setUserBirthday(new Date()); int res = userDao.saveUser(user); System.out.println("影响数据库记录的行数:"+res); System.out.println("插入的主键值:"+user.getUserId()); } /** * 测试更新 */ @Test public void testUpdate() { User user = userDao.findById(63); user.setUserBirthday(new Date()); user.setUserSex("女"); int res = userDao.updateUser(user); System.out.println(res); } /** * 测试删除 */ @Test public void testDelete() { int res = userDao.deleteUser(63); System.out.println(res); } /** * 测试查询使用聚合函数 */ @Test public void testFindTotal() { int res = userDao.findTotal(); System.out.println(res); } /** * 测试模糊查询 */ @Test public void testFindByName() { List<User> users = userDao.findByName("%m%"); for(User user : users) { System.out.println(user); } } private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; @Before//junit 的注解 public void init()throws Exception{ //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); //3.创建 session session = factory.openSession(); //4.创建代理对象 userDao = session.getMapper(IUserDao.class); } @After//junit 的注解 public void destroy()throws Exception { //提交事务 session.commit(); //释放资源 session.close(); //关闭流 in.close(); }
@Results 注解
代替的是标签
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或@Results(@Result())
@Resutl 注解
代替了 标签和标签
@Result 中 属性介绍:
@One 注解(一对一)
@Many 注解(多对一)
加载账户信息并且加载该账户的用户信息,并且可以延迟加载
/** * * <p>Title: User</p> * <p>Description: 用户的实体类</p> * <p>Company: http://www.itheima.com/ </p> */ public class User implements Serializable { private Integer userId; private String userName; private Date userBirthday; private String userSex; private String userAddress; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + ", userBirthday=" + userBirthday + ", userSex="+ userSex + ", userAddress=" + userAddress + "]"; } } /** * * <p>Title: Account</p> * <p>Description: 账户的实体类</p> * <p>Company: http://www.itheima.com/ </p> */ public class Account implements Serializable { private Integer id; private Integer uid; private Double money; //多对一关系映射:从表方应该包含一个主表方的对象引用 private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account [id=" + id + ", uid=" + uid + ", money=" + money + "]"; } }
/** * * <p>Title: IAccountDao</p> * <p>Description: 账户的持久层接口</p> * <p>Company: http://www.itheima.com/ </p> */ 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(column="uid", property="user", one=@One(select="com.itheima.dao.IUserDao.findById", fetchType=FetchType.LAZY) ) }) List<Account> findAll();
/** * * <p>Title: IUserDao</p> * <p>Description: 用户的持久层接口</p> * <p>Company: http://www.itheima.com/ </p> */ 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="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday") }) List<User> findAll(); /** * 根据 id 查询一个用户 * @param userId * @return */ @Select("select * from user where id = #{uid} ") @ResultMap("userMap") User findById(Integer userId); }
/** * * <p>Title: User</p> * <p>Description: 用户的实体类</p> * <p>Company: http://www.itheima.com/ </p> */ public class User implements Serializable { private Integer userId; private String userName; private Date userBirthday; private String userSex; private String userAddress; //一对多关系映射:主表方法应该包含一个从表方的集合引用 private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + ", userBirthday=" + userBirthday + ", userSex="+ userSex + ", userAddress=" + userAddress + "]"; } }
* <p>Title: IUserDao</p> * <p>Description: 用户的持久层接口</p> * <p>Company: http://www.itheima.com/ </p> */ 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="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday"), @Result(column="id",property="accounts", many=@Many( select="com.itheima.dao.IAccountDao.findByUid",fetchType=FetchType.LAZY) ) }) List<User> findAll(); } --------------------------------------------------- @Many: 相当于<collection>的配置 select 属性:代表将要执行的 sql 语句 fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
/** * * <p>Title: IAccountDao</p> * <p>Description: 账户的持久层接口</p> * <p>Company: http://www.itheima.com/ </p> */ public interface IAccountDao { /** * 根据用户 id 查询用户下的所有账户 * * @param userId * @return */ @Select("select * from account where uid = #{uid} ") List<Account> findByUid(Integer userId); }
/** * * <p>Title: MybatisAnnotationCRUDTest</p> * <p>Description: mybatis 的注解 crud 测试</p> * <p>Company: http://www.itheima.com/ </p> */ public class UserTest { /** * 测试查询所有 */ @Test public void testFindAll() { List<User> users = userDao.findAll(); // for(User user : users) { // System.out.println("-----每个用户的内容-----"); // System.out.println(user); // System.out.println(user.getAccounts()); // } } private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; @Before//junit 的注解 public void init()throws Exception{ //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); //3.创建 session session = factory.openSession(); //4.创建代理对象 userDao = session.getMapper(IUserDao.class); } @After//junit 的注解 public void destroy()throws Exception { //提交事务 session.commit(); //释放资源 session.close(); //关闭流 in.close(); } }
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 -->
<setting name="cacheEnabled" value="true"/>
</settings>
/**
*
* <p>Title: IUserDao</p>
* <p>Description: 用户的持久层接口</p>
* <p>Company: http://www.itheima.com/ </p>
*/
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。