MyBatis 注解配置
Employee
package com.example.demo.domain; import java.io.Serializable; public class Employee implements Serializable {
private Integer id;
private String loginname;
private String password;
private String name;
private String sex;
private Integer age;
private String phone;
private double sal;
private String state; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLoginname() {
return loginname;
} public void setLoginname(String loginname) {
this.loginname = loginname;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public double getSal() {
return sal;
} public void setSal(double sal) {
this.sal = sal;
} public String getState() {
return state;
} public void setState(String state) {
this.state = state;
}
}
EmployeeMapper
package com.example.demo.mapper; import com.example.demo.domain.Employee;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider; import java.util.HashMap;
import java.util.List;
import java.util.Map; public interface EmployeeMapper {
List<Employee> selectEmployeeByIdLike(HashMap<String,Object> params);
List<Employee> selectEmployeeByLoginLike(HashMap<String,Object> params);
List<Employee> selectEmployeeChoose(HashMap<String,Object> params);
List<Employee> selectEmployeeLike(HashMap<String,Object> params);
Employee selectEmployeeById(Integer id);
void updateEmployeeIfNecessary(Employee employee);
List<Employee> selectEmployeeIn(List<Integer> ids);
List<Employee> selectEmployeeLikeNmae(Employee employee);
@SelectProvider(type = EmployeeSqlProvider.class,method = "selectWithParam")
List<Employee> selectWithParam(Map<String,Object> param);
@InsertProvider(type = EmployeeSqlProvider.class,method = "insert")
int insert(Employee employee);
@UpdateProvider(type = EmployeeSqlProvider.class,method = "update")
void update(Employee employee);
@DeleteProvider(type = EmployeeSqlProvider.class,method = "delete")
void delete(Map<String,Object> param);
}
EmployeeSqlProvider
package com.example.demo.mapper; import com.example.demo.domain.Employee;
import org.apache.ibatis.jdbc.SQL; import java.util.Map; public class EmployeeSqlProvider {
public String selectWithParam(Map<String,Object> param){
return new SQL(){
{
SELECT("*");
FROM("tb_employee");
if(param.get("id")!=null){
WHERE(" id=#{id} ");
}
if(param.get("loginname")!=null){
WHERE(" loginname=#{loginname} ");
}
if(param.get("password")!=null){
WHERE(" password=#{password} ");
}
if(param.get("name")!=null){
WHERE(" name=#{name} ");
}
if(param.get("sex")!=null){
WHERE(" sex=#{sex} ");
}
if(param.get("age")!=null){
WHERE(" age=#{age} ");
}
if(param.get("phone")!=null){
WHERE(" phone=#{phone} ");
}
if(param.get("sal")!=null){
WHERE(" sal=#{sal} ");
}
if(param.get("state")!=null){
WHERE(" state=#{state} ");
}
}
}.toString();
}
public String insert(Employee employee){
return new SQL(){
{
INSERT_INTO("tb_employee");
if(employee.getLoginname()!=null){
VALUES("loginname","#{loginname}");
}
if(employee.getPassword()!=null){
VALUES("password","#{password}");
}
if(employee.getName()!=null){
VALUES("name","#{name}");
}
if(employee.getSex()!=null){
VALUES("sex","#{sex}");
}
if(employee.getAge()!=null){
VALUES("age","#{age}");
}
if(employee.getPhone()!=null){
VALUES("phone","#{phone}");
}
if(employee.getSal()>=){
VALUES("sal","#{sal}");
}
if(employee.getState()!=null){
VALUES("state","#{state}");
}
}
}.toString();
}
public String update(Employee employee){
return new SQL(){
{
UPDATE("tb_employee");
if(employee.getLoginname()!=null){
SET("loginname=#{loginname}");
}if(employee.getPassword()!=null){
SET("password=#{password}");
}if(employee.getName()!=null){
SET("name=#{name}");
}if(employee.getSex()!=null){
SET("sex=#{sex}");
}if(employee.getAge()!=null){
SET("age=#{age}");
}if(employee.getPhone()!=null){
SET("phone=#{phone}");
}if(employee.getSal()>=){
SET("sal=#{sal}");
}if(employee.getState()!=null){
SET("state=#{state}");
}
WHERE(" id=#{id} ");
}
}.toString();
}
public String delete(Map<String,Object> param){
return new SQL(){
{
DELETE_FROM("tb_employee");
if(param.get("id")!=null){
WHERE(" id=#{id} ");
}if(param.get("loginname")!=null){
WHERE(" loginname=#{loginname} ");
}if(param.get("password")!=null){
WHERE(" password=#{password} ");
}if(param.get("name")!=null){
WHERE(" name=#{name} ");
}if(param.get("sex")!=null){
WHERE(" sex=#{sex} ");
}if(param.get("age")!=null){
WHERE(" age=#{age} ");
}if(param.get("phone")!=null){
WHERE(" phone=#{phone} ");
}if(param.get("sal")!=null){
WHERE(" sal=#{sal} ");
}if(param.get("state")!=null){
WHERE(" state=#{state} ");
}
}
}.toString();
}
}
AnnotationTest
package com.example.demo.test; import com.example.demo.domain.Clazz;
import com.example.demo.domain.Employee;
import com.example.demo.domain.Person;
import com.example.demo.domain.User;
import com.example.demo.factory.FKSqlSessionFactory;
import com.example.demo.mapper.ClazzMapper;
import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.mapper.PersonMapper;
import com.example.demo.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession; import java.util.HashMap;
import java.util.List;
import java.util.Map; public class AnnotationTest {
public static void main(String[] args){
SqlSession session= FKSqlSessionFactory.getSqlSession();
// UserMapper mapper=session.getMapper(UserMapper.class);
AnnotationTest test=new AnnotationTest();
// test.testInsert(session,mapper);
// test.testSelectById(session,mapper);
// test.testUpdateUser(session,mapper);
// test.testDeleteUser(session,mapper);
// test.testSelectAll(session,mapper);
// PersonMapper mapper=session.getMapper(PersonMapper.class);
// test.testOneToOne(session,mapper);
// ClazzMapper mapper=session.getMapper(ClazzMapper.class);
// test.testOneToMany(session,mapper);
EmployeeMapper mapper=session.getMapper(EmployeeMapper.class);
// test.testDynamicSQL(session,mapper);
test.testDynamicInsert(session,mapper);
// test.testDynamicUpdate(session,mapper);
// test.testDynamicDelete(session,mapper);
session.close();
}
public void testInsert(SqlSession session,UserMapper mapper){
User user=new User();
user.setName("leon");
user.setSex("男");
user.setAge();
mapper.saveUser(user);
session.commit();
}
public void testSelectById(SqlSession session,UserMapper mapper){
User user=mapper.selectById();
System.out.println(user.getName()+" "+user.getSex()+" "+user.getAge());
}
public void testUpdateUser(SqlSession session,UserMapper mapper){
User user=mapper.selectById();
System.out.println(user.getName()+" "+user.getSex()+" "+user.getAge());
user.setName("kate");
user.setSex("女");
user.setAge();
mapper.modifyUser(user);
session.commit();
}
public void testDeleteUser(SqlSession session,UserMapper mapper){
mapper.removeUser();
session.commit();
}
public void testSelectAll(SqlSession session,UserMapper mapper){
List<User> users=mapper.selectAll();
users.forEach(user -> System.out.println(user.getName()+" "+user.getSex()+" "+user.getAge()));
}
public void testOneToOne(SqlSession session, PersonMapper mapper){
Person person=mapper.selectById();
System.out.println(person.getName()+" "+person.getSex()+" "+person.getAge());
System.out.println(person.getCard().getCode());
}
public void testOneToMany(SqlSession session, ClazzMapper mapper){
Clazz clazz=mapper.selectById();
System.out.println(clazz.getCode()+" "+clazz.getName());
clazz.getStudents().forEach(student -> System.out.println(student.getName()+" "+student.getSex()+" "+student.getAge()));
}
public void testDynamicSQL(SqlSession session, EmployeeMapper mapper){
Map<String,Object> map=new HashMap<String,Object>();
map.put("state","ACTIVE");
map.put("loginname","jack");
map.put("password","");
List<Employee> list=mapper.selectWithParam(map);
list.forEach(employee -> System.out.println(employee.getName()+" "+employee.getSex()+" "+employee.getAge()+" "+employee.getSal()+" "+employee.getState()));
}
public void testDynamicInsert(SqlSession session,EmployeeMapper mapper){
Employee employee=new Employee();
employee.setName("tom");
employee.setSex("男");
employee.setAge();
employee.setLoginname("tom");
employee.setPassword("");
employee.setSal();
employee.setPhone("");
employee.setState("ACTIVE");
mapper.insert(employee);
session.commit();
}
public void testDynamicUpdate(SqlSession session,EmployeeMapper mapper){
Employee employee=mapper.selectEmployeeById();
employee.setName("汤姆");
employee.setSal();
mapper.update(employee);
session.commit();
}
public void testDynamicDelete(SqlSession session,EmployeeMapper mapper){
Map<String,Object> map=new HashMap<String,Object>();
map.put("loginname","tom");
map.put("password","");
mapper.delete(map);
session.commit();
} }
UserMapper
package com.example.demo.mapper; import com.example.demo.domain.User;
import org.apache.ibatis.annotations.*; import java.util.List; public interface UserMapper {
@Insert("insert into tb_user(name,sex,age) values(#{name},#{sex},#{age})")
@Options(useGeneratedKeys = true,keyProperty = "id")
int saveUser(User user);
@Delete("delete from tb_user where id=#{id}")
int removeUser(@Param("id")Integer id);
@Update("update tb_user set name=#{name},sex=#{sex},age=#{age} where id=#{id}")
void modifyUser(User user);
@Select("select * from tb_user where id=#{id}")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "sex",property = "sex"),
@Result(column = "age",property = "age")
})
User selectById(Integer id);
@Select("select * from tb_user")
List<User> selectAll();
User selectUserById(Integer id);
List<User> selectAllUser();
void deleteUserById(Integer id);
}
ClazzMapper
package com.example.demo.mapper; import com.example.demo.domain.Clazz;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType; public interface ClazzMapper {
Clazz selectClazzById(Integer id);
@Select("select * from tb_clazz where id=#{id}")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "code",property = "code"),
@Result(column = "id",property = "students",
many = @Many(select = "com.example.demo.mapper.StudentMapper.selectByClazzId",fetchType = FetchType.LAZY))
})
Clazz selectById(Integer id);
}
StudentMapper
package com.example.demo.mapper; import com.example.demo.domain.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select; import java.util.List; public interface StudentMapper {
Student selectStudentByClazzId(Integer id);
Student selectStudentById(Integer id);
@Select("select * from tb_student where clazz_id=#{id}")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "sex",property = "sex"),
@Result(column = "age",property = "age"),
})
List<Student> selectByClazzId(Integer id);
}
PersonMapper
package com.example.demo.mapper; import com.example.demo.domain.Person;
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; public interface PersonMapper {
Person selectPersonById(Integer id);
@Select("select * from tb_person where id=#{id}")
@Results({
@Result(id=true,column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "sex",property = "sex"),
@Result(column = "age",property = "age"),
@Result(column = "card_id",property = "card",
one = @One(select = "com.example.demo.mapper.CardMapper.selectById",fetchType = FetchType.EAGER))
})
Person selectById(Integer id);
}
CardMapper
package com.example.demo.mapper; import com.example.demo.domain.Card;
import org.apache.ibatis.annotations.Select; public interface CardMapper {
Card selectCardById(Integer id);
@Select("select * from tb_card where id=#{id}")
Card selectById(Integer id);
}
Card
package com.example.demo.domain; import java.io.Serializable; public class Card implements Serializable {
private Integer id;
private String code; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
}
}
Person
package com.example.demo.domain; import java.io.Serializable; public class Person implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private Card card; public Card getCard() {
return card;
} public void setCard(Card card) {
this.card = card;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}
Clazz
package com.example.demo.domain; import java.io.Serializable;
import java.util.List; public class Clazz implements Serializable {
private Integer id;
private String code;
private String name;
private List<Student> students; public List<Student> getStudents() {
return students;
} public void setStudents(List<Student> students) {
this.students = students;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Student
package com.example.demo.domain; import java.io.Serializable; public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private Clazz clazz; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public Clazz getClazz() {
return clazz;
} public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
}
User
package com.example.demo.domain; import java.io.Serializable; public class User implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}
FKSqlSessionFactory
package com.example.demo.factory; 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; public class FKSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory=null;
static {
try {
InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
MyBatis 注解配置的更多相关文章
- MyBatis 注解配置及动态SQL
一.注解配置 目前MyBatis支持注解配置,用注解方式来替代映射文件,但是注解配置还是有点不完善,在开发中使用比较少,大部分的企业还是在用映射文件来进行配置.不完善的地方体现在于当数据表中的字段 ...
- Spring Boot中使用MyBatis注解配置详解(1)
之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...
- Spring Boot中使用MyBatis注解配置详解
传参方式 下面通过几种不同传参方式来实现前文中实现的插入操作. 使用@Param 在之前的整合示例中我们已经使用了这种最简单的传参方式,如下: @Insert("INSERT INTO US ...
- 08—mybatis注解配置二
动态sql mybatis的注解也支持动态sql.mybatis提供了各种注解,如@InsertProvider.@UpdateProvider.@DeleteProvider和@SelectProv ...
- 07—mybatis注解配置一
常用注解Select:映射查询的sql语句.SelectProvider:Select语句的动态sql映射.允许指定一个类名和一个方法在执行时返回运行的查询语句.有两个属性:type和mehtod,t ...
- Spring Boot教程(三十九)使用MyBatis注解配置详解(2)
增删改查 MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置,在之前的示例中演示了@Insert,下面针对User表做一组最基本的增删改查作为示例: public interface U ...
- Spring Boot教程(三十八)使用MyBatis注解配置详解(1)
之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...
- MyBatis注解配置动态SQL
MySQL创建表 DROP TABLE IF EXISTS `tb_employee`; CREATE TABLE `tb_employee` ( `id` int(11) NOT NULL AUTO ...
- 09—mybatis注解配置join查询
今天来聊mybatis的join查询,怎么说呢,有的时候,join查询确实能提升查询效率,今天举个left join的例子,来看看mybatis的join查询. 就不写的很细了,把主要代码贴出来了. ...
随机推荐
- 【慕课网实战】Spark Streaming实时流处理项目实战笔记六之铭文升级版
铭文一级: 整合Flume和Kafka的综合使用 avro-memory-kafka.conf avro-memory-kafka.sources = avro-sourceavro-memory-k ...
- python在使用redis时zadd错误
最近在看<redis实战>,在写zadd时报错 Traceback (most recent call last): File "<stdin>", lin ...
- Ng第七课:正则化与过拟合问题 Regularization/The Problem of Overfitting
7.1 过拟合的问题 7.2 代价函数 7.3 正则化线性回归 7.4 正则化的逻辑回归模型 7.1 过拟合的问题 如果我们有非常多的特征,我们通过学习得到的假设预测可能能够非常好地适应训练 ...
- SCI投稿过程总结、投稿状态解析、拒稿后对策及接受后期相关问答
SCI投稿过程总结.投稿状态解析.拒稿后对策及接受后期相关问答 http://muchong.com/t-9174366-1 SCI投稿过程总结.投稿状态解析.拒稿后处理对策及接受后期相关问答综合 ...
- spring处理线程并发
http://www.open-open.com/bbs/view/1320130410702
- HDU1025贫富平衡
做01背包做到的这个LIS,常见的n2会超时,所以才有nlogn可行 先来介绍一下n2 dp[i] 表示该序列以a[i]为结尾的最长上升子序列的长度 所以第一层循环循环数组a,第二层循环循环第i个元素 ...
- JVM虚拟机---本地接口(我还不太会)
转载http://www.newhua.com/2008/0328/33542_2.shtml Java本地接口(Java Native Interface (JNI))允许运行在Java虚拟机(Ja ...
- ArrayBlockingQueue源码解析(1)
此文已由作者赵计刚授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 注意:在阅读本文之前或在阅读的过程中,需要用到ReentrantLock,内容见<第五章 Reentr ...
- 同一域名基于源ip地址分配给不同ip的dns配置--bind9.8.2
1.安装bind.略. 2./etc/named.conf配置文件. // named.conf // // Provided by Red Hat bind package to configure ...
- 利用Python做绝地科学家(外挂篇)
i春秋作家:奶权 前言 玩吃鸡时间长的鸡友们 应该都知道现在的游戏环境非常差 特别在高端局 神仙满天飞 搞得很多普通玩家非常没有游戏体验 因为吃鸡的火爆 衍生出了一条巨大的外挂利益链 导致市面上出 ...