单表的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. 直方图histeq

    histeq的原理: [MN]=size(H); [counts,x]=imhist(H);%H是读取的图像,imhist是对图像直方图进行统计,其中count,是每个灰度值得个数,x代表灰度值.一般 ...

  2. VS2015生成代码图

    熟悉代码调用流程,可以在调试结束前显示代码图,操作位置: 比如开源的caffe_ocr的代码图:

  3. PyCharm 上传项目到码云托管平台

    码云平台设置: >先到码云 https://gitee.com/ 注册账号 >创建项目,选择合适项目,点击加号 >填写项目的基础信息 在码云上就创建了项目 >安装 Git    ...

  4. MYSQL的索引类型:PRIMARY, INDEX,UNIQUE,FULLTEXT,SPAIAL 区别与使用场合

    normal 普通索引   unique 唯一的,不允许重复的索引 该字段信息保证不会重复例如身份证号用作索引时,可设置为unique full textl 全文搜索的索引 FULLTEXT 用于搜索 ...

  5. Hadoop3.1.1源码Client详解 : 写入准备-RPC调用与流的建立

    该系列总览: Hadoop3.1.1架构体系——设计原理阐述与Client源码图文详解 : 总览 关于RPC(Remote Procedure Call),如果没有概念,可以参考一下RMI(Remot ...

  6. 多进程pipe

    pipe模块可以实现进程之间数据传递 栗子1:3个进程,一个主进程,2个子进程,三个管道,三个进程通过3个管道连接,主进程发一个信息,通过2个子进程转发,最后回到主进程输出 import multip ...

  7. 吴裕雄 python 神经网络——TensorFlow 循环神经网络处理MNIST手写数字数据集

    #加载TF并导入数据集 import tensorflow as tf from tensorflow.contrib import rnn from tensorflow.examples.tuto ...

  8. makefile的书写

    工作中会遇到makefile的书写,有必要做一些笔记.尽管网上有”万能模板“可以使用,但我觉得还是有必要从最基础的写起. 平常在windows下开发,不知道自己用过makefile,其实大部分IDE里 ...

  9. Java面向对象封装优化1_this(Python中的self)

    1. 类 package cn.itcast.day06.demo03; /* 问题描述:定义Person的年龄时,无法阻止不合理的数值被设置进来. 解决方案:用private关键字将需要保护的成员变 ...

  10. 使用 swiper 制作 导航,点击项居中

    目的:导航有多个,被点击的项居中显示. html: <div class="swiper-container"> <div class="swiper- ...