博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring系列教程七: Spring 整合mybatis的四种方式
阅读量:6192 次
发布时间:2019-06-21

本文共 18687 字,大约阅读时间需要 62 分钟。

hot3.png

一、使用采用数据映射器(MapperFactoryBean)的方式注解实现整合mybatis

不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数,项目目录如下

147c96042d22590781feab650455bf88240.jpg

第一步、导入jar包

src/main/java
**/*.xml
src/main/resources
**/*.properties
**/*.xml
aopalliance
aopalliance
1.0
org.aspectj
aspectjweaver
1.6.9
commons-dbcp
commons-dbcp
1.4
commons-logging
commons-logging
1.2
commons-pool
commons-pool
1.6
org.apache.logging.log4j
log4j
2.6.1
org.mybatis
mybatis
3.4.1
org.mybatis
mybatis-spring
2.0.1
mysql
mysql-connector-java
5.1.6
org.springframework
spring-context
4.3.6.RELEASE
org.springframework
spring-jdbc
4.3.6.RELEASE
org.springframework
spring-tx
4.3.6.RELEASE
c3p0
c3p0
0.9.1.2
compile

第二步、创建学生实体类

package com.cc.entity;public class Student {    private  int id;    private  String stuno;    private  String name;    private  String classid;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getStuno() {        return stuno;    }    public void setStuno(String stuno) {        this.stuno = stuno;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getClassid() {        return classid;    }    public void setClassid(String classid) {        this.classid = classid;    }    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", stuno='" + stuno + '\'' +                ", name='" + name + '\'' +                ", classid='" + classid + '\'' +                '}';    }}

第三步、创建Mapper接口,在接口中用注解的方式实现sql语句

package com.cc.dao;import com.cc.entity.Student;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import java.util.List;public interface StudentMapper {    @Select("select * from student where id=#{id}")    Student findById(@Param("id") int id);    @Select("select * from student")    List
selectAll();}

那么还有一个问题,我想在注解中实现动态查询那怎么办???案例如下

@Mapperpublic interface DemandCommentMapper extends BaseMapper
{ @Select("SELECT " + "a.id as 'id',a.create_date as 'createDate',a.content as 'content'," + "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId'," + "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar'," + "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' " + "FROM t_demand_comment a " + "LEFT JOIN t_user b ON b.id = a.from_uid " + "LEFT JOIN t_user c ON c.id = a.to_uid " + "WHERE a.demand_id = #{demandId} " + "ORDER BY a.create_date ASC" + "LIMIT #{startNo},#{pageSize}") public List
listDemandComment(@Param("demandId") Long demandId,                              @Param("startNo") Integer pageNo,                              @Param("pageSize") Integer pageSize);

这样整个语句是写死的,如果我想根据pageNo与pageSize是否为空来判断是否需要分页,该怎么做呢?如果使用xml来配置的话可以用

LIMIT #{startNo},#{pageSize}

如果是用 这种该如何做呢?方法:用script标签包围,然后像xml语法一样书写

@Mapperpublic interface DemandCommentMapper extends BaseMapper
{ @Select("
") public List
listDemandComment(@Param("demandId") Long demandId,                              @Param("startNo") Integer pageNo,                              @Param("pageSize") Integer pageSize);

项目实例

@Select("")    public List
getTaobao(@Param("status") Integer status);

在这里还碰到一个问题就是报错:Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'status' in 'class java.lang.Interger'

出现原因:这里出现的问题是在DAO方法中定义的参数 与 实体中定义的属性不一致 导致的。

解决方案:dao层加@Param("userId")注解即可(实例中就是加上@Param("status"))

public List<DictItem> selectKeyByUserId(@Param("userId") long userId);

第四步、在service层实现接口类

package com.cc.service;import com.cc.entity.Student;import java.util.List;public interface StudentService {    Student findById(int id);    List
selectAll();}
package com.cc.service;import com.cc.dao.StudentMapper;import com.cc.entity.Student;import java.util.List;public class StudentServiceImpl implements StudentService {    private  StudentMapper studentMapper;    public void setStudentMapper(StudentMapper studentMapper) {        this.studentMapper = studentMapper;    }    @Override    public Student findById(int id) {        return (Student) studentMapper.findById(id);    }    @Override    public List
selectAll() { return studentMapper.selectAll(); }}

第五步、配置ApplicationContext.xml文件

第六步、配置db.properties文件

#mysql jdbc freshjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8jdbc.username=rootjdbc.password=root

第七步、测试类

import com.cc.entity.Student;import com.cc.service.StudentService;import com.cc.service.StudentServiceImpl;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;public class Testdemo1 {    @Test    public  void test(){         ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");         StudentService studentService =ac.getBean("studentService", StudentServiceImpl.class);         Student student=studentService.findById(5);         System.out.println(student);         List
studentList=studentService.selectAll(); for (Student stu: studentList) { System.out.println(stu); } }}

c0a9136ed65b80f390764a5ec861336042d.jpg

二、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession

目录结构如下

ffcc14666859ec1f54829c9ec93e90d56a2.jpg

第一步、导入jar包

src/main/java
**/*.xml
src/main/resources
**/*.properties
**/*.xml
aopalliance
aopalliance
1.0
org.aspectj
aspectjweaver
1.6.9
commons-dbcp
commons-dbcp
1.4
commons-logging
commons-logging
1.2
commons-pool
commons-pool
1.6
org.apache.logging.log4j
log4j
2.6.1
org.mybatis
mybatis
3.4.1
org.mybatis
mybatis-spring
2.0.1
mysql
mysql-connector-java
5.1.6
org.springframework
spring-context
4.3.6.RELEASE
org.springframework
spring-jdbc
4.3.6.RELEASE
org.springframework
spring-tx
4.3.6.RELEASE
Spring
Spring_mybatis_01
1.0-SNAPSHOT
compile

第二步、创建实体类

package cc.entity;public class Student {    private  int id;    private  String stuno;    private  String name;    private  String classid;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getStuno() {        return stuno;    }    public void setStuno(String stuno) {        this.stuno = stuno;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getClassid() {        return classid;    }    public void setClassid(String classid) {        this.classid = classid;    }    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", stuno='" + stuno + '\'' +                ", name='" + name + '\'' +                ", classid='" + classid + '\'' +                '}';    }}

第三步、创建StudentDao接口,已经其实现类

package cc.dao;import com.cc.entity.Student;public interface StudentDao {    Student findById(int id);}
package cc.dao;import com.cc.dao.StudentDao;import com.cc.entity.Student;import org.mybatis.spring.support.SqlSessionDaoSupport;public class StudentImpl extends SqlSessionDaoSupport implements StudentDao {    @Override    public Student findById(int id) {        return (Student) getSqlSession().selectOne("com.cc.dao.StudentMapper.findById",id);    }}

第四步、创建映射器接口,已经其mapper配置文件

package cc.dao;import com.cc.entity.Student;public interface StudentMapper {    Student findById(int id);}

第五步、实现ApplicationContext配置文件和mybatis核心配置文件

第六步、配置数据文件

#mysql jdbc freshjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8jdbc.username=rootjdbc.password=root

第七步、在test文件用junit4实现单元测试

import cc.dao.StudentImpl;import com.cc.entity.Student;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {    @org.junit.Test    public  void test(){        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");        StudentImpl stu=ac.getBean("studentDao", StudentImpl.class);        Student student=stu.findById(6);        System.out.println(student);    }}

bc4234995edffe1c30e6f7ba724f03e322c.jpg

三、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate

这种平时都用的很少,所以这里我就不写了

四、采用扫描接口的方式实现Spring整合mybatis(最常用)

9ddc376b2d7f7e022988144560bc9d42fae.jpg

第一步、导入依赖配置

src/main/java
**/*.xml
src/main/resources
**/*.properties
**/*.xml
aopalliance
aopalliance
1.0
org.aspectj
aspectjweaver
1.6.9
commons-dbcp
commons-dbcp
1.4
commons-logging
commons-logging
1.2
commons-pool
commons-pool
1.6
org.apache.logging.log4j
log4j
2.6.1
org.mybatis
mybatis
3.4.1
org.mybatis
mybatis-spring
2.0.1
mysql
mysql-connector-java
5.1.6
org.springframework
spring-context
4.3.6.RELEASE
org.springframework
spring-jdbc
4.3.6.RELEASE
org.springframework
spring-tx
4.3.6.RELEASE
Spring
Spring_mybatis_01
1.0-SNAPSHOT
compile
com.mchange
c3p0
0.9.5.2
log4j
log4j
1.2.12

第二步、编写实体类

package cc.entity;public class Student {    private  int id;    private  String stuno;    private  String name;    private  String classid;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getStuno() {        return stuno;    }    public void setStuno(String stuno) {        this.stuno = stuno;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getClassid() {        return classid;    }    public void setClassid(String classid) {        this.classid = classid;    }    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", stuno='" + stuno + '\'' +                ", name='" + name + '\'' +                ", classid='" + classid + '\'' +                '}';    }}

第三步、配置StudentMapper接口

package cc.dao;import com.cc.entity.Student;public interface StudentMapper {    Student findById(int id);}

第四步、配置mybatis映射文件和核心配置文件

第五步、配置数据库文件

#mysql jdbc freshjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8jdbc.username=rootjdbc.password=root

第六步、配置ApplicationContext.xml

第七步、编写测试类

import cc.service.StudentService;import com.cc.entity.Student;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Testone {    @Test    public void test(){        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");        StudentService studentService = (StudentService) ac.getBean("studentService");        Student student=studentService.findById(4);        System.out.println(student);    }}

04831cc6400506cf1429c238e084394a437.jpg

转载于:https://my.oschina.net/u/4115727/blog/3053847

你可能感兴趣的文章
运行预构建 Linux 映像的 Windows Azure 虚拟机中的交换空间 – 第 1 部分
查看>>
Sqrt(x) II
查看>>
关于jvm运行时时区的总结
查看>>
编程算法 - 两个升序列的同样元素 代码(C)
查看>>
Regular Expression Matching
查看>>
Phalcon 訪问控制列表 ACL(Access Control Lists ACL)
查看>>
无线局域网技术
查看>>
【转载】LINUX下安装wget命令(SFTP实现法)
查看>>
做单一定要看数据,提防数据,特别是周三周四
查看>>
Android Categroy 详解大全
查看>>
java中的定时器
查看>>
开源前端和服务器程序项目
查看>>
iOS app原型工具Briefs
查看>>
COCO数据集的下载以及姿态关键点的数据处理
查看>>
建造者模式(C++)
查看>>
使用vmware安装ubuntu不能上网
查看>>
【无私分享:从入门到精通ASP.NET MVC】从0开始,一起搭框架、做项目 (11)文件管理...
查看>>
js 小知识
查看>>
WEBSOCKET协议判断 握手及反馈
查看>>
corosync 源代码分析 2
查看>>