首页 > 技术文章 > spring和mybatis的集合

lihp-java 2021-03-06 19:59 原文

1. 先建maven项目

2. 加入maven依赖

  1)spring依赖

       2)mybatis依赖

       3)mysql驱动

    4)spring的事务依赖

  5)mybatis和spring集成的依赖:mybatis官方提供的,用来在spring项目中创建mybatis的SqlSessionFactory,dao对象的。
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5   <modelVersion>4.0.0</modelVersion>
 6 
 7   <groupId>com.bjpowernode</groupId>
 8   <artifactId>ch07-spring-mybatis</artifactId>
 9   <version>1.0-SNAPSHOT</version>
10 
11 
12   <properties>
13     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
14     <maven.compiler.source>1.8</maven.compiler.source>
15     <maven.compiler.target>1.8</maven.compiler.target>
16   </properties>
17 
18   <dependencies>
19     <dependency>
20       <groupId>junit</groupId>
21       <artifactId>junit</artifactId>
22       <version>4.11</version>
23       <scope>test</scope>
24     </dependency>
25     <!--spring的核心ioc-->
26     <dependency>
27       <groupId>org.springframework</groupId>
28       <artifactId>spring-context</artifactId>
29       <version>5.2.5.RELEASE</version>
30     </dependency>
31     <!--做spring事务要用到的tx,jdbc-->
32     <dependency>
33       <groupId>org.springframework</groupId>
34       <artifactId>spring-tx</artifactId>
35       <version>5.2.5.RELEASE</version>
36     </dependency>
37     <dependency>
38       <groupId>org.springframework</groupId>
39       <artifactId>spring-jdbc</artifactId>
40       <version>5.2.5.RELEASE</version>
41     </dependency>
42     <!--mybatis依赖-->
43     <dependency>
44       <groupId>org.mybatis</groupId>
45       <artifactId>mybatis</artifactId>
46       <version>3.5.1</version>
47     </dependency>
48     <!--mybatis,spring集成的依赖-->
49     <dependency>
50       <groupId>org.mybatis</groupId>
51       <artifactId>mybatis-spring</artifactId>
52       <version>1.3.1</version>
53     </dependency>
54     <!--mysql驱动-->
55     <dependency>
56       <groupId>mysql</groupId>
57       <artifactId>mysql-connector-java</artifactId>
58       <version>5.1.9</version>
59     </dependency>
60     <!--阿里公司的数据连接池-->
61     <dependency>
62       <groupId>com.alibaba</groupId>
63       <artifactId>druid</artifactId>
64       <version>1.1.12</version>
65     </dependency>
66   </dependencies>
67 
68   <build>
69     <!--目的是把src/main/java目录中的xml文件包含到输出结果中-->
70     <resources>
71       <resource>
72         <directory>src/main/java</directory><!--所在的目录-->
73         <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
74           <include>**/*.properties</include>
75           <include>**/*.xml</include>
76         </includes>
77         <filtering>false</filtering>
78       </resource>
79     </resources>
80 
81     <plugins>
82       <plugin>
83         <artifactId>maven-compiler-plugin</artifactId>
84         <version>3.1</version>
85         <configuration>
86           <source>1.8</source>
87           <target>1.8</target>
88         </configuration>
89       </plugin>
90     </plugins>
91   </build>
92 </project>
View Code

3. 创建实体类

 1 package com.bjpowernode.domain;
 2 
 3 public class Student {
 4     private Integer id;
 5     private String name;
 6     private String email;
 7     private Integer age;
 8 
 9     public Student() {
10     }
11 
12     public Student(Integer id, String name, String email, Integer age) {
13         this.id = id;
14         this.name = name;
15         this.email = email;
16         this.age = age;
17     }
18 
19     public Integer getId() {
20         return id;
21     }
22 
23     public void setId(Integer id) {
24         this.id = id;
25     }
26 
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 
35     public String getEmail() {
36         return email;
37     }
38 
39     public void setEmail(String email) {
40         this.email = email;
41     }
42 
43     public Integer getAge() {
44         return age;
45     }
46 
47     public void setAge(Integer age) {
48         this.age = age;
49     }
50 
51     @Override
52     public String toString() {
53         return "student{" +
54                 "id=" + id +
55                 ", name='" + name + '\'' +
56                 ", email='" + email + '\'' +
57                 ", age=" + age +
58                 '}';
59     }
60 }
View Code

4.创建dao接口和mapper文件

 1 package com.bjpowernode.dao;
 2 
 3 import com.bjpowernode.domain.Student;
 4 
 5 import java.util.List;
 6 
 7 public interface StudentDao {
 8     List<Student> selectStudents();
 9     int insertStudent(Student student);
10 }
View Code
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.bjpowernode.dao.StudentDao">
 6     <select id="selectStudents" resultType="com.bjpowernode.domain.Student">
 7         select id,name,email,age from student order by id desc
 8     </select>
 9 
10     <insert id="insertStudent">
11         insert into student values(#{id},#{name},#{email},#{age})
12     </insert>
13 </mapper>
View Code
5. 创建mybatis主配置文件
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <!--mybatis-3-config.dtd约束文件信息-->
 6 <configuration>
 7     <!--settings:控制mybatis的全局行为-->
 8     <settings>
 9         <!--设置mybatis输出日志到控制台-->
10         <setting name="logImpl" value="STDOUT_LOGGING"/>
11     </settings>
12 <!--    <typeAliases>
13         <typeAlias  type="com.bjpowernode.domain.Student"/>
14     </typeAliases>-->
15     <!--sql映射文件的位置(sql mapper 的位置)-->
16     <!--一个mapper标签指定一个文件的位置,从类路径开始的路径信息
17     类路径:编译后target/classes下面的路径
18     -->
19     <mappers>
20         <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
21     </mappers>
22 </configuration>
View Code

6.创建Service接口和实现类,属性是dao

 1 package com.bjpowernode.service;
 2 
 3 import com.bjpowernode.domain.Student;
 4 
 5 import java.util.List;
 6 
 7 public interface MyService {
 8     List<Student> selectStudents();
 9     int insertStudent(Student student);
10 }
View Code
 1 package com.bjpowernode.service;
 2 
 3 import com.bjpowernode.dao.StudentDao;
 4 import com.bjpowernode.domain.Student;
 5 
 6 import java.util.List;
 7 
 8 public class MyServiceImpl implements MyService {
 9     private StudentDao studentDao = null;
10 
11     public void setStudentDao(StudentDao studentDao) {
12         this.studentDao = studentDao;
13     }
14 
15     @Override
16     public List<Student> selectStudents() {
17         List<Student> students = studentDao.selectStudents();
18         return students;
19     }
20 
21     @Override
22     public int insertStudent(Student student) {
23         int num = studentDao.insertStudent(student);
24         return num;
25     }
26 }
View Code
7. 创建spring的配置文件:声明mybatis的对象交给spring创建
jdbc.username = root
jdbc.url = jdbc:mysql://localhost:3306/springdb
jdbc.password = 123456
jdbc.maxcon = 20
View Code
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
 6     <!--使用属性配置文件来编译修改数据库的配置内容-->
 7     <context:property-placeholder location="classpath:jdbc.properties"/>
 8     <!--声明数据源,链接数据库-->
 9     <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
10         <!--使用属性配置文件的数据,语法${key}-->
11         <property name="url" value="${jdbc.url}"/>
12         <property name="username" value="${jdbc.username}"/>
13         <property name="password" value="${jdbc.password}"/>
14         <property name="maxActive" value="${jdbc.maxcon}"/>
15     </bean>
16     <!--声明的是mybatis提供的SqlSessionFactoryBean实现类-->
17     <!--把原来SqlSessionFactory需要的数据库链接信息,mapper文件存放位置赋值-->
18     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
19         <property name="dataSource" ref="myDataSource"/>
20         <property name="configLocation" value="classpath:mybatis_conf.xml"/>
21     </bean>
22     <!--声明dao对象-->
23     <!--使用SqlSession的getMapper(StudentDao.class)
24     MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象
25     -->
26     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
27         <!--指定SqlSessionFactory对象的id-->
28         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
29         <!--
30         指定包名,包名是dao接口所在的包名,MapperScannerConfigurer会扫描这个包中的所有
31         接口,把每个接口都执行一次getMapper()方法,得到每个接口的dao对象
32         创建好的dao对象放到spring容器中,dao对象的默认名称是接口名首字母小写
33         -->
34         <property name="basePackage" value="com.bjpowernode.dao"/>
35     </bean>
36     <!--声明service对象-->
37     <bean id="myService" class="com.bjpowernode.service.MyServiceImpl">
38         <property name="studentDao" ref="studentDao"/>
39     </bean>
40 </beans>
View Code
8. 创建测试类,获取Service对象,通过Service调用,完成数据库的访问
 1 package com.bjpowernode;
 2 
 3 import com.bjpowernode.dao.StudentDao;
 4 import com.bjpowernode.domain.Student;
 5 import com.bjpowernode.service.MyService;
 6 import com.bjpowernode.utils.MybatisUtils;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.junit.Test;
 9 import org.springframework.context.ApplicationContext;
10 import org.springframework.context.support.ClassPathXmlApplicationContext;
11 
12 import java.util.List;
13 
14 public class MyTest01 {
15     @Test
16     public void test01(){
17         String conf = "applicationContext.xml";
18         ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
19 /*        String [] lists = ac.getBeanDefinitionNames();
20         for(String s:lists){
21             System.out.println(s);
22         }
23 
24         StudentDao dao = (StudentDao) ac.getBean("studentDao");
25         List<Student> list = dao.selectStudents();
26         for (Student s:list){
27             System.out.println(s);
28         }*/
29         MyService myService = (MyService) ac.getBean("myService");
30         Student student = new Student(1009,"wangxx","dd@qq.com",87);
31         /**
32          * spring和mybatis集合,事务自动提交
33          */
34         int num = myService.insertStudent(student);
35         System.out.println(num);
36     }
37 
38     @Test
39     public void testSelectAll(){
40         String config = "applicationContext.xml";
41         ApplicationContext ac = new ClassPathXmlApplicationContext(config);
42         MyService myService = (MyService) ac.getBean("myService");
43         List<Student> students = myService.selectStudents();
44         for(Student stu:students){
45             System.out.println(stu);
46         }
47     }
48 }
View Code

 

 

推荐阅读