这几年来注解开发越来越流行,Mybatis 也可以使用注解开发方式,这样我们就可以减少编写 Mapper 映射文件了。

1.常用注解说明

@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用

2.使用Mybatis注解实现基本CRUD

2.1查询数据库

2.2创建maven工程导入jar包的坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId>
<artifactId>day04_eesy_03annotation_mybaitis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies> </project>

2.3配置数据库连接信息

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy_mybatis
jdbc.username=root
jdbc.password=123456
<?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>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!-- 指定带有注解的dao接口所在位置 -->
<mappers>
<mapper class="com.itheima.dao.IUserDao"></mapper>
</mappers>
</configuration>

2.4编写实体类

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date; public class User implements Serializable { private Integer id;
private String username;
private String address;
private String sex;
private Date birthday; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}

2.5使用注解方式开发持久层接口

package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.Select; import java.util.List; /**
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
}

2.6编写测试方法

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.InputStream;
import java.util.List; public class MybatisAnnoTest { /**
* 测试基于注解的mybatis使用
* @param args
*/
public static void main(String[] args) throws Exception{
//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();
}
}

2.7CURD

package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import java.util.List; /**
* @Select @Insert @Update @Delete
*/
public interface IUserDao {
/**
* 查询所有用户
*
* @return
*/
@Select("select * from user")
List<User> findAll(); /**
* 保存用户
*
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user); @Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user); @Delete("delete from user where id=#{id} ")
void deleteUser(Integer userId); @Select("select * from user where id=#{id} ")
User findById(Integer userId); @Select("select * from user where username like #{username} ")
List<User> findUserByName(String username); @Select("select count(*) from user ")
int findTotalUser(); }
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 SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao; @Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class); } @After
public void destroy() throws Exception {
session.commit();
session.close();
in.close();
} @Test
public void testSave() {
User user = new User();
user.setUsername("mybatis annotation");
user.setAddress("nanchang");
userDao.saveUser(user);
} @Test
public void testUpdate() {
User user = new User();
user.setId(60);
user.setUsername("mybatis annotation");
user.setAddress("nanchang");
user.setSex("男");
userDao.updateUser(user);
} @Test
public void testDelete() {
userDao.deleteUser(60);
} @Test
public void testFindOne() {
User user = userDao.findById(58);
System.out.println(user);
} @Test
public void testFindByName() {
List<User> users = userDao.findUserByName("%mybatis%");
for (User user : users) {
System.out.println(user);
}
} @Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
} }

3.在注解配置中解决数据库字段名和实体类字段名不对应问题

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List; public class User implements Serializable { private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday; 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 String getUserAddress() {
return userAddress;
} public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
} public String getUserSex() {
return userSex;
} public void setUserSex(String userSex) {
this.userSex = userSex;
} public Date getUserBirthday() {
return userBirthday;
} public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
} @Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}

package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*; import java.util.List; /**
* @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"})
@ResultMap("userMap")
User findById(Integer userId); /**
* 根据用户名称模糊查询
*
* @param username
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findUserByName(String username); }

4.多表1对1查询

4.1实体类

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List; public class User implements Serializable { private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday; 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 String getUserAddress() {
return userAddress;
} public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
} public String getUserSex() {
return userSex;
} public void setUserSex(String userSex) {
this.userSex = userSex;
} public Date getUserBirthday() {
return userBirthday;
} public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
} @Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}
package com.itheima.domain;

import java.io.Serializable;

public class Account implements Serializable {

    private Integer id;
private Integer uid;
private Double money; //多对一(mybatis中称之为一对一)的映射:一个账户只能属于一个用户
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 +
'}';
}
}

4.2添加账户的持久层接口并使用注解配置

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(); /**
* 根据用户id查询账户信息
* @param userId
* @return
*/
@Select("select * from account where uid = #{userId}")
List<Account> findAccountByUid(Integer userId);
}
package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*; import java.util.List; /**
* @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"})
@ResultMap("userMap")
User findById(Integer userId); /**
* 根据用户名称模糊查询
*
* @param username
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findUserByName(String username); }

4.3测试类

package com.itheima.test;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
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.InputStream;
import java.util.List; public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IAccountDao accountDao; @Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
accountDao = session.getMapper(IAccountDao.class);
} @After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
} @Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
for(Account account : accounts){
System.out.println("----每个账户的信息-----");
System.out.println(account);
System.out.println(account.getUser());
}
} }

5.使用注解实现一对多复杂关系映射

需求:
  查询用户信息时,也要查询他的账户列表。使用注解方式实现。
分析:
  一个用户具有多个账户信息,所以形成了用户(User)与账户(Account)之间的一对多关系。

5.1User实体类加入List<Account>

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List; 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;
} 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 String getUserAddress() {
return userAddress;
} public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
} public String getUserSex() {
return userSex;
} public void setUserSex(String userSex) {
this.userSex = userSex;
} public Date getUserBirthday() {
return userBirthday;
} public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
} @Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}

5.2编写用户的持久层接口并使用注解配置

package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType; import java.util.List; /**
* @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"),
@Result(property = "accounts",column = "id",
many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List<User> findAll(); /**
* 根据id查询用户
*
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
// @ResultMap(value = {"userMap"})
@ResultMap("userMap")
User findById(Integer userId); /**
* 根据用户名称模糊查询
*
* @param username
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findUserByName(String username); }

5.3编写账户的持久层接口并使用注解配置

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 { /**
* 根据用户id查询账户信息
* @param userId
* @return
*/
@Select("select * from account where uid = #{userId}")
List<Account> findAccountByUid(Integer userId);
}

5.4测试类

 @Test
public void findAll() {
List<User> users = userDao.findAll();
for (User u :users ) {
System.out.println("每个用户的信息。。。");
System.out.println(u);
System.out.println(u.getAccounts()); }
}

6.mybatis基于注解的二级缓存

6.1在SqlMapConfig

<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 -->
<setting name="cacheEnabled" value="true"/>
</settings>

6.2在持久层接口中使用注解配置二级缓存

@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}

22_7mybaits注解开发的更多相关文章

  1. SpringMVC注解开发初步

    一.(补充)视图解析器---XmlViewResolver 作用:分离配置信息. 在视图解析器---BeanNameViewResolver的基础之上进行扩充,新建一个myView.xml分离信息 在 ...

  2. SpringMVC的注解开发入门

    1.Spring MVC框架简介 支持REST风格的URL 添加更多注解,可完全注解驱动 引入HTTP输入输出转换器(HttpMessageConverter) 和数据转换.格式化.验证框架无缝集成 ...

  3. Struts2框架之-注解开发

    Struts2主要解决了从JSP到Action上的流程管理,如何进行Uri和action类中每个方法的绑定这是重点,在这里先简单看一下配置文件中的简单配置: <span style=" ...

  4. Java自定义注解开发

    一.背景 最近在自己搞一个项目时,遇到可需要开发自定义注解的需求,对于没有怎么关注这些java新特性的来说,比较尴尬,索性就拿出一些时间,来进行研究下自定义注解开发的步骤以及使用方式.今天在这里记下, ...

  5. Annotation(四)——Struts2注解开发

    Hibernate和Spring框架的开发前边总结了,这次看一下流行的MVC流程框架Struts2的注解开发吧.Struts2主要解决了从JSP到Action上的流程管理,如何进行Uri和action ...

  6. Annotation(三)——Spring注解开发

    Spring框架的核心功能IoC(Inversion of Control),也就是通过Spring容器进行对象的管理,以及对象之间组合关系的映射.通常情况下我们会在xml配置文件中进行action, ...

  7. Annotation(一)——注解开发介绍

    <p>在编程中,一直强调的一点就是注释的编写,注释的规范等等.尤其是越是核心,程序越复杂,逻辑越多的清空下,注释的编写对我们以后的阅读代码,维护软件起着至关重要的作用.一款软件有着好的注释 ...

  8. spring注解开发中常用注解以及简单配置

    一.spring注解开发中常用注解以及简单配置 1.为什么要用注解开发:spring的核心是Ioc容器和Aop,对于传统的Ioc编程来说我们需要在spring的配置文件中邪大量的bean来向sprin ...

  9. 使用Java注解开发自动生成SQL

    使用注解开发的好处就是减少配置文件的使用.在实际过程中,随着项目越来越复杂,功能越来越多,会产生非常多的配置文件.但是,当配置文件过多,实际维护过程中产生的问题就不容易定位,这样就会徒劳的增加工作量. ...

随机推荐

  1. 鸟哥私房菜基础篇:磁碟配额(Quota)与进阶文件系统管理习题

    猫宁!!! 参考:http://cn.linux.vbird.org/linux_basic/0420quota.php 1-在前一章的第一个大量新增帐号范例中, 如果我想要让每个用户均具有 soft ...

  2. libev 源码解析

    一  libev简介 libev是一个轻量级的事件通知库,具备支持多种事件通知能力,通过对libev的源码的阅读,可以清楚了解事件通知实现内部机制. 二 核心数据结构 在libev中关键的数据结构是, ...

  3. [转帖]InfluxDB 1.2.0安装及新旧版本的注意事项

    InfluxDB 1.2.0安装及新旧版本的注意事项 http://haibing.org/245?zwlqby=npztq3 挺好的文章 很好的解决了 上一个文档里面 关于 web admin 的问 ...

  4. 记日杂-log4net组件使用

    下面我给大家介绍一下记日杂-log4net组件使用,当程序发布有服务器上,有时出现了错误, 都不知道出现在那,所以log4net组件很好解决这个问题. 1.添加开发包,并对log4net.dll的引用 ...

  5. Vue里标签嵌套限制问题解决------解析DOM模板时注意事项:

    受到html本身的一些限制,像<ul>.<ol>.<table>.<select>这样的元素里允许包含的元素有限制,而另一些像<option> ...

  6. signalfx的中间件监控指标so cool

    signalfx的中间件监控指标so cool www.jianshu.com   对于我们做运维的来说,监控是最基本的东西,不过在初创公司很多计划是跟不上项目架构变化的,项目中会不断加入各种服务和组 ...

  7. NYOJ 石子合并(一) 区间dp入门级别

    描述    有N堆石子排成一排,每堆石子有一定的数量.现要将N堆石子并成为一堆.合并的过程只能每次将相邻的两堆石子堆成一堆,每次合并花费的代价为这两堆石子的和,经过N-1次合并后成为一堆.求出总的代价 ...

  8. ASP.NET Core MVC里面Razor如何获取URL参数

    原文:ASP.NET Core MVC里面Razor如何获取URL参数 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https:// ...

  9. tracert命令详解_tracert结果详解_tracert命令使用详解

    17:06:40 正在等待客服售后工程师令狐冲接入,您可以先简单描述所要咨询的问题,如果长时间没有响应,您也可以 重新选择客服 . 17:06:42 您好,客服售后工程师令狐冲为您服务.售后工程师令狐 ...

  10. Excel学习笔记:行列转换

    目录 offset函数 行列转换的三种方式 1.右键转置 2.转置公式TRANSPOSE 3.引用函数OFFSET+ROWS/COLUMN(支持随时更新数据) 一行(列)转多行多列 offset函数 ...