单表的CRUD注解开发:

User实体类:

package com.zyb.pojo;

import java.io.Serializable;
import java.util.Date; public class User implements Serializable {
private Integer id;
private String username;
private String sex;
private String address;
private Date birthday; public User() {
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", birthday=" + 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 getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

UserDao:

package com.zyb.dao;

import com.zyb.pojo.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; public interface UserDao {
@Select("select * from my_user")
List<User> selAllUsers(); @Insert("insert into my_user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday}) ")
void saveUser(User u); @Update("update my_user set username=#{username} where id=#{id}")
void updateUser(User user); @Delete("delete from my_user where id=#{id}")
void deleteUserById(int userId); @Select("select * from my_user where id=#{id}")
User selUserById(int userId); @Select("select * from my_user where username like '%${value}%'")
// @Select("select * from my_user where username like #{username}")
List<User> selUserByName(String userName); @Select("select count(*) from my_user")
int usersNum();
}

测试:

package com.zyb.test;

import com.zyb.dao.UserDao;
import com.zyb.pojo.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.InputStream;
import java.util.Date;
import java.util.List; public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private UserDao userDao; @Before
public void init()throws Exception{
in = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(UserDao.class);
} @After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
} @Test
public void testSelAllUsers(){
List<User> users=userDao.selAllUsers();
users.forEach(x-> System.out.println(x));
} @Test
public void testSaveUser(){
User user= new User();
user.setSex("男");
user.setAddress("地球");
user.setBirthday(new Date());
user.setUsername("zhang");
userDao.saveUser(user);
} @Test
public void testUpdateUser(){
User user = new User();
user.setId(58);
user.setUsername("liu");
user.setSex("女");
userDao.updateUser(user); } @Test
public void testDeleteUserById(){
userDao.deleteUserById(58);
} @Test
public void testSelUserById(){
User user= userDao.selUserById(52);
System.out.println(user);
} @Test
public void testSelUserByName(){
List<User> users=userDao.selUserByName("王");
users.forEach(x-> System.out.println(x));
} @Test
public void testUsersNum(){
int num=userDao.usersNum();
System.out.println(num);
} }

多表注解操作:

逻辑:一个用户可以有多个账户,一个账户只能被一个用户拥有

User实体类多了一个:

新增的Account实体类:

package com.zyb.pojo;

import java.io.Serializable;

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;
} @Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
} 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;
} public Account() {
}
}

AccountDao:

package com.zyb.dao;

import com.zyb.pojo.Account;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType; import java.util.List; public interface AccountDao { @Select("select * from my_account")
@Results(id="accountMap",value = {
@Result(property = "id",column = "id",id=true),
@Result(property = "uid",column = "uid"),
@Result(property = "money",column = "money"),
@Result(property = "user",column = "uid",one = @One(select = "com.zyb.dao.UserDao.selUserById",fetchType= FetchType.EAGER)) })
List<Account> selAllAccounts2User(); @Select("select * from my_account where uid=#{uid}")
@ResultMap("accountMap")
List<Account> selAccountsByUid();
}

UserDao:

package com.zyb.dao;

import com.zyb.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType; import java.util.List; public interface UserDao {
@Select("select * from my_user")
@Results(id="userMap" ,value={
@Result(property = "userId",column="id" ,id=true),
@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.zyb.dao.AccountDao.selAccountsByUid",fetchType = FetchType.LAZY)) })
List<User> selAllUsers(); @Select("select * from my_user where id=#{id}")
@ResultMap(value = {"userMap"})
User selUserById(int userId); @Select("select * from my_user where username like #{username}")
@ResultMap(value = {"userMap"})
List<User> selUserByName(String userName); }

Dao层分析:

Results点进去的源码:

id属性、Result类型的value数组

 Result类型点进去的源码:

One或Many点进去的源码:

注意在使用注解是mybatis-config.xml的配置

day04-MyBatis的注解开发的更多相关文章

  1. spring boot整合mybatis基于注解开发以及动态sql的使用

    让我们回忆一下上篇博客中mybatis是怎样发挥它的作用的,主要是三类文件,第一mapper接口,第二xml文件,第三全局配置文件(application.properties),而今天我们就是来简化 ...

  2. mybatis的注解开发之三种动态sql

    脚本sql XML配置方式的动态SQL我就不讲了,有兴趣可以自己了解,下面是用<script>的方式把它照搬过来,用注解来实现.适用于xml配置转换到注解配置 @Select(" ...

  3. mybatis学习:mybatis的注解开发和编写dao实现类的方式入门

    一.使用注解则不需要创建映射配置文件:即xxxDao.xml javaBean为什么要实现Serializable接口? Java的"对象序列化"能让你将一个实现了Serializ ...

  4. Mybatis使用注解开发(未完)

    使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心 注解在接口实现 @Select("SELECT * FROM user") Lis ...

  5. MyBatis使用注解开发

  6. mybatis学习:mybatis的注解开发CRUD操作

    Dao层: public interface IUserDao { /** * 查询所有结果 * @return */ @Select("select * from user") ...

  7. Mybatis注解开发模糊查询

    Mybatis注解开发模糊查询 一般在使用mybatis时都是采用xml文件保存sql语句 这篇文章讲一下在使用mybatis的注解开发时,如何进行模糊查询 模糊查询语句写法(在@Select注解中) ...

  8. 学习MyBatis必知必会(7)~注解开发、动态SQL

    一.MyBatis的注解开发 开发中推荐是使用xml文件配置 1.配置映射关系[使用注解的方式]: <!-- 全局的配置文件 --> <configuration> <! ...

  9. Spring+SpringMVC+MyBatis深入学习及搭建(十六)——SpringMVC注解开发(高级篇)

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7085268.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十五)——S ...

  10. mybatis多参数传递,延迟加载,缓存,注解开发

    1.Mybatis的多参数传递方式 需求:更具id 和 名字查询用户: select * from user where id = ? and name = ?: 1):QueryVo 或者 User ...

随机推荐

  1. python面试的100题(1)

    题目:有一个jsonline格式的文件file.txt大小约为10K def get_lines(): with open('file.txt','rb') as f: return f.readli ...

  2. Linux - Shell - 在多个文件中查找关键字

    1. 概述 在多个文件中 查找内容 2. 想干啥 目的 在 多个文件 中, 查找内容 准备 之前在 单个文件里 查找过内容 工具 awk 前提 文件有固定格式 查找时有字段的要求 例子 # print ...

  3. BT详解,BT原理

    请参考以下链接: https://www.cnblogs.com/EasonJim/p/6601146.html

  4. Centos6.10-FastDFS-Tracker-Nginx示例配置

    nginx 安装过程<详见> 1.进入工作目录 cd /usr/local/nginx/conf 2.创建子目录 mkdir configs 3.创建storage代理配置 cd conf ...

  5. 零基础入门python爬虫(一)

    ✍写在前面: 欢迎加入纯干货技术交流群Disaster Army:317784952 接到5月25日之前要交稿的任务我就一门心思想写一篇爬虫入门的文章,可是我并不会.还好有将近一个月的时间去学习,于是 ...

  6. 放眼全球,关注游戏质量变化:腾讯WeTest发布《2019中国移动游戏质量白皮书》

    2019是中国游戏市场,尤其是手游市场称得上是跌宕起伏的一年,同时也是各大厂商推陈出新突破过去的一年.面对竞争激烈的市场,手游厂商们不仅着眼于游戏质量的提升,更是将一众优秀的国产游戏带入到了海外市场, ...

  7. SQL语句,pymysql模块,sql注入问题

    一.完整版SQL语句的查询 select distinct post,avg(salary) from table where id > 1 group by post` having avg( ...

  8. [采坑记录] OneDrive同步失败 不能自动上传 不能同步 不能登陆

    虽然OneDrive送的空间并不大 但是用来传文档什么的还是够了 但是国内各种不舒服 比如说登陆不上(其他的微软系应用解决方法同理) 原因是因为DNS污染的问题 默认电脑链接上网络之后 DNS是路由器 ...

  9. C语言与汇编的嵌入式编程:求100以内素数

    写汇编之前,需要搞清楚C语言代码的写法,这里以最简单的算法举例说明 C代码如下: #include <stdio.h> void main(){ int i,j; ; ;i<=;i+ ...

  10. PHP定时执行任务的3种方法详解

    转载 https://www.jb51.net/article/76720.htm 更新时间:2015年12月21日 10:38:56   作者:PHP淮北   我要评论 PHP不支持多线程,有时候处 ...