spring-mybatis 结合 配置文件 及 简单 test

1...pom.xml 配置文件

  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.wsc</groupId>
  8   <artifactId>testSpring_mybatis</artifactId>
  9   <version>1.0-SNAPSHOT</version>
 10   <packaging>war</packaging>
 11 
 12   <name>testSpring_mybatis Maven Webapp</name>
 13   <!-- FIXME change it to the project's website -->
 14   <url>http://www.example.com</url>
 15 
 16   <properties>
 17     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 18     <maven.compiler.source>1.7</maven.compiler.source>
 19     <maven.compiler.target>1.7</maven.compiler.target>
 20   </properties>
 21 
 22   <dependencies>
 23     <dependency>
 24       <groupId>junit</groupId>
 25       <artifactId>junit</artifactId>
 26       <version>4.12</version>
 27       <scope>test</scope>
 28     </dependency>
 29       <dependency>
 30           <groupId>org.mybatis</groupId>
 31           <artifactId>mybatis</artifactId>
 32           <version>3.4.5</version>
 33       </dependency>
 34       <dependency>
 35           <groupId>org.springframework</groupId>
 36           <artifactId>spring-context</artifactId>
 37           <version>5.0.2.RELEASE</version>
 38       </dependency>
 39       <dependency>
 40           <groupId>c3p0</groupId>
 41           <artifactId>c3p0</artifactId>
 42           <version>0.9.1.2</version>
 43       </dependency>
 44       <dependency>
 45           <groupId>commons-dbcp</groupId>
 46           <artifactId>commons-dbcp</artifactId>
 47           <version>1.4</version>
 48       </dependency>
 49       <dependency>
 50           <groupId>mysql</groupId>
 51           <artifactId>mysql-connector-java</artifactId>
 52           <version>5.1.6</version>
 53       </dependency>
 54       <dependency>
 55           <groupId>org.springframework</groupId>
 56           <artifactId>spring-jdbc</artifactId>
 57           <version>5.0.2.RELEASE</version>
 58       </dependency>
 59       <dependency>
 60           <groupId>org.springframework</groupId>
 61           <artifactId>spring-test</artifactId>
 62           <version>5.0.2.RELEASE</version>
 63       </dependency>
 64       <dependency>
 65           <groupId>org.mybatis</groupId>
 66           <artifactId>mybatis-spring</artifactId>
 67           <version>1.3.1</version>
 68       </dependency>
 69       <dependency>
 70           <groupId>log4j</groupId>
 71           <artifactId>log4j</artifactId>
 72           <version>1.2.17</version>
 73       </dependency>
 74       <dependency>
 75           <groupId>org.springframework</groupId>
 76           <artifactId>spring-tx</artifactId>
 77           <version>5.0.2.RELEASE</version>
 78       </dependency>
 79       <dependency>
 80           <groupId>org.aspectj</groupId>
 81           <artifactId>aspectjweaver</artifactId>
 82           <version>1.8.9</version>
 83       </dependency>
 84       <!--web引入依赖-->
 85 
 86       <dependency>
 87           <groupId>org.springframework</groupId>
 88           <artifactId>spring-webmvc</artifactId>
 89           <version>5.0.2.RELEASE</version>
 90       </dependency>
 91       <dependency>
 92           <groupId>javax.servlet</groupId>
 93           <artifactId>servlet-api</artifactId>
 94           <version>2.5</version>
 95           <scope>provided</scope>
 96       </dependency>
 97       <dependency>
 98           <groupId>javax.servlet</groupId>
 99           <artifactId>jsp-api</artifactId>
100           <version>2.0</version>
101           <scope>provided</scope>
102       </dependency>
103       <!--引入标签库-->
104 
105       <dependency>
106           <groupId>jstl</groupId>
107           <artifactId>jstl</artifactId>
108           <version>1.2</version>
109       </dependency>
110   </dependencies>
111 
112   <build>
113     <finalName>testSpring_mybatis</finalName>
114     <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
115       <plugins>
116         <plugin>
117           <artifactId>maven-clean-plugin</artifactId>
118           <version>3.1.0</version>
119         </plugin>
120         <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
121         <plugin>
122           <artifactId>maven-resources-plugin</artifactId>
123           <version>3.0.2</version>
124         </plugin>
125         <plugin>
126           <artifactId>maven-compiler-plugin</artifactId>
127           <version>3.8.0</version>
128         </plugin>
129         <plugin>
130           <artifactId>maven-surefire-plugin</artifactId>
131           <version>2.22.1</version>
132         </plugin>
133         <plugin>
134           <artifactId>maven-war-plugin</artifactId>
135           <version>3.2.2</version>
136         </plugin>
137         <plugin>
138           <artifactId>maven-install-plugin</artifactId>
139           <version>2.5.2</version>
140         </plugin>
141         <plugin>
142           <artifactId>maven-deploy-plugin</artifactId>
143           <version>2.8.2</version>
144         </plugin>
145       </plugins>
146     </pluginManagement>
147   </build>
148 </project>
pom.xml

2...sqlMapperingConfig.xml

 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 <configuration>
 6     <properties resource="jdbc.properties"></properties>
 7     <environments default="development">
 8         <environment id="development">
 9             <transactionManager type="JDBC"/>
10             <dataSource type="POOLED">
11                 <property name="driver" value="${jdbc.driver}"/>
12                 <property name="url" value="${jdbc.url}"/>
13                 <property name="username" value="${jdbc.name}"/>
14                 <property name="password" value="${jdbc.password}"/>
15             </dataSource>
16         </environment>
17     </environments>
18     <mappers>
19        <package name="com.wsc.dao"></package>
20     </mappers>
21 </configuration>
sqlMapperingConfig.xml

3...spring-mvc.xml

 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        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/context
 9        http://www.springframework.org/schema/context/spring-context.xsd
10        http://www.springframework.org/schema/mvc
11        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12     <!-- 扫描包 创建类对象 -->
13     <context:component-scan base-package="com.wsc.controller"></context:component-scan>
14     <!--视图解析器-->
15     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16     <property name="prefix" value="/pages/"></property>
17     <property name="suffix" value=".jsp"></property>
18     </bean>
19     <!--注解驱动-->
20     <mvc:annotation-driven></mvc:annotation-driven>
21     <!--静态资源放行-->
22 <!--    <mvc:resources mapping="/js/*" location="/js/"></mvc:resources>-->
23    <mvc:default-servlet-handler></mvc:default-servlet-handler>
24 </beans>
spring-mvc.xml

4...jdbc.properties

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/studentdb
3 jdbc.name=root
4 jdbc.password=wsc
jdbc.properties

5...applicationContext.xml

 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" xmlns:tx="http://www.springframework.org/schema/tx"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/context
 9        http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
10     <!--引入外部资源-->
11         <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
12     <!--数据源-->
13     <bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
14         <property name="driverClassName" value="${jdbc.driver}"></property>
15         <property name="url" value="${jdbc.url}"></property>
16         <property name="username" value="${jdbc.name}"></property>
17         <property name="password" value="${jdbc.password}"></property>
18     </bean>
19     <!--创建sqlSeesionFactor对象-->
20     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
21         <!--引入数据源-->
22         <property name="dataSource" ref="DataSource"></property>
23     </bean>
24     <!--扫描dao层的包   创建动态代理对象  存入spring容器中-->
25     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
26         <property name="basePackage" value="com.wsc.dao"></property>
27     </bean>
28     <!--业务层配置开始-->
29     <!--扫描包 创建servie 层所有的类对象-->
30     <context:component-scan base-package="com.wsc.service"></context:component-scan>
31     <!--1 事物管理器对象-->
32     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
33         <property name="dataSource" ref="DataSource"></property>
34     </bean>
35     <!--2 事物管理增强对象-->
36     <tx:advice transaction-manager="transactionManager" id="txx">
37         <tx:attributes>
38             <!--该类方法  只读  如果有事物   加入事物执行 -->
39             <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
40             <tx:method name="query*" read-only="true" propagation="SUPPORTS"></tx:method>
41             <tx:method name="get*" read-only="true" propagation="SUPPORTS"></tx:method>
42 
43             <!--其它方法  非只读  创建事物  -->
44            <tx:method name="*" read-only="false" propagation="REQUIRED" ></tx:method>
45         </tx:attributes>
46     </tx:advice>
47     <!--3  aop配置 切面配置-->
48     <aop:config>
49 <!--        <aop:pointcut id="txx"  expression="execution(* com.wsc.service.impl.*.*(..))"/>-->
50        <aop:advisor advice-ref="txx" pointcut="execution(* com.wsc.service.impl.*.*(..))"></aop:advisor>
51     </aop:config>
52 </beans>
applicationContext.xml

6...web.xml

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7     <!--配置一个全局的参数  指定spring 容器配置文件-->
 8     <context-param>
 9         <param-name>contextConfigLocation</param-name>
10         <param-value>classpath:applicationContext.xml</param-value>
11     </context-param>
12     <filter>
13         <filter-name>CharacterEncodingFilter</filter-name>
14         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
15         <init-param>
16         <param-name>encoding</param-name>
17         <param-value>utf-8</param-value>
18     </init-param>
19     </filter>
20     <filter-mapping>
21         <filter-name>CharacterEncodingFilter</filter-name>
22         <url-pattern>/*</url-pattern>
23     </filter-mapping>
24     <!--配置监听器  创建spring 对象-->
25     <listener>
26         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
27     </listener>
28     <servlet>
29         <servlet-name>DispatcherServlet</servlet-name>
30         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
31         <init-param>
32             <param-name>contextConfigLocation</param-name>
33             <param-value>classpath:spring-mvc.xml</param-value>
34         </init-param>
35     </servlet>
36 <servlet-mapping>
37     <servlet-name>DispatcherServlet</servlet-name>
38     <url-pattern>/</url-pattern>
39 </servlet-mapping>
40 </web-app>
web.xml

7...spring --》test

 1 package com.wsc.test;
 2 
 3 import com.wsc.dao.StudentDao;
 4 import com.wsc.domain.Student;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import java.util.List;
12 
13 /**
14  * @version 1.0
15  * @ClassName TestSpingMybaties
16  * @Description TODO
17  * @Author WSC
18  * @Date 2019/7/12 13:41
19  **/
20 //@RunWith(SpringJUnit4ClassRunner.class)
21 //@ContextConfiguration("classpath:applicationContext.xml")
22 public class TestSpingMybaties {
23 @Test
24     public void testSprMybatis(){
25         ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
26         StudentDao bean = classPathXmlApplicationContext.getBean(StudentDao.class);
27         List<Student> allStudent = bean.findAllStudent();
28         for(Student student:allStudent){
29             System.out.println(student);
30     }
31 
32 }
33 }
spring-test

8...mybatis  ---》test

 1 package com.wsc.test;
 2 
 3 import com.wsc.dao.StudentDao;
 4 import com.wsc.domain.Student;
 5 import org.apache.ibatis.session.SqlSession;
 6 import org.apache.ibatis.session.SqlSessionFactory;
 7 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 8 import org.junit.Test;
 9 
10 import java.io.InputStream;
11 import java.util.List;
12 
13 /**
14  * @version 1.0
15  * @ClassName TestSpring_mybatis
16  * @Description TODO
17  * @Author WSC
18  * @Date 2019/7/12 13:12
19  **/
20 public class TestSpring_mybatis {
21     @Test
22     public void testStudent(){
23         InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("sqlMapperingConfig.xml");
24         SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
25         SqlSession sqlSession = build.openSession();
26         StudentDao mapper = sqlSession.getMapper(StudentDao.class);
27         List<Student> allStudent = mapper.findAllStudent();
28         for(Student student:allStudent){
29             System.out.println(student);
30         }
31         sqlSession.close();
32     }
33 }
mybatis-test

9...spring-mybatis-test

 1 package com.wsc.test;
 2 
 3 import com.wsc.domain.Student;
 4 import com.wsc.service.StudentService;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import java.util.Date;
12 import java.util.List;
13 
14 /**
15  * @version 1.0
16  * @ClassName TestSM
17  * @Description TODO
18  * @Author WSC
19  * @Date 2019/7/12 14:16
20  **/
21 @RunWith(SpringJUnit4ClassRunner.class)
22 @ContextConfiguration("classpath:applicationContext.xml")
23 public class TestSM {
24     @Autowired
25     StudentService studentService;
26     @Test
27     public void testFindAll(){
28         List<Student> allStudent = studentService.findAllStudent();
29         for(Student student:allStudent){
30             System.out.println(student);
31         }
32     }
33     @Test
34     public void testFindById(){
35         Student byId = studentService.findById(2);
36         System.out.println(byId);
37     }
38     @Test
39     public void testDrop(){
40         studentService.drop(24);
41     }
42     @Test
43     public void testUpdate(){
44         Student student = new Student();
45         student.setStudentNo(29);
46         student.setStudentName("s");
47         studentService.update(student);
48     }
49     @Test
50     public void testAdd(){
51         Student student = new Student();
52         student.setStudentName("晚饭");
53         student.setAge(20);
54         student.setClassNo(3);
55         Date date = new Date();
56         student.setBoreDate(date);
57         studentService.add(student);
58     }
59     @Test
60     public void testFindByName(){
61         List<Student> byName = studentService.findByName("国");
62         for(Student student:byName){
63             System.out.println(student);
64         }
65     }
66 }
注解 test

10...Student

 1 package com.wsc.domain;
 2 
 3 import java.util.Date;
 4 
 5 /**
 6  * @version 1.0
 7  * @ClassName Student
 8  * @Description TODO
 9  * @Author WSC
10  * @Date 2019/7/12 11:09
11  **/
12 public class Student {
13     private int studentNo;
14     private String studentName;
15     private int age;
16     private Date boreDate;
17     private int classNo;
18 
19     public Student() {
20         super();
21     }
22 
23     public Student(int studentNo, String studentName, int age, Date boreDate, int classNo) {
24         super();
25         this.studentNo = studentNo;
26         this.studentName = studentName;
27         this.age = age;
28         this.boreDate = boreDate;
29         this.classNo = classNo;
30     }
31 
32     public int getStudentNo() {
33         return studentNo;
34     }
35 
36     public void setStudentNo(int studentNo) {
37         this.studentNo = studentNo;
38     }
39 
40     public String getStudentName() {
41         return studentName;
42     }
43 
44     public void setStudentName(String studentName) {
45         this.studentName = studentName;
46     }
47 
48     public int getAge() {
49         return age;
50     }
51 
52     public void setAge(int age) {
53         this.age = age;
54     }
55 
56     public Date getBoreDate() {
57         return boreDate;
58     }
59 
60     public void setBoreDate(Date boreDate) {
61         this.boreDate = boreDate;
62     }
63 
64     public int getClassNo() {
65         return classNo;
66     }
67 
68     public void setClassNo(int calssNo) {
69         this.classNo = calssNo;
70     }
71 
72     @Override
73     public String toString() {
74         return "Student [studentNo=" + studentNo + ", studentName=" + studentName + ", age=" + age + ", boreDate="
75                 + boreDate + ", calssNo=" + classNo + "]";
76     }
77 }
Student 实体类

11...dao

 1 package com.wsc.dao;
 2 
 3 import com.wsc.domain.Student;
 4 import org.apache.ibatis.annotations.Delete;
 5 import org.apache.ibatis.annotations.Insert;
 6 import org.apache.ibatis.annotations.Select;
 7 import org.apache.ibatis.annotations.Update;
 8 
 9 import java.util.List;
10 
11 public interface StudentDao {
12     @Select("select * from student")
13     public List<Student> findAllStudent();
14     @Select("select * from student where studentNo=#{studentNo}")
15     public Student findById(Integer studentNo);
16     @Delete("delete from student where studentNo=#{studentNo}")
17     public void drop(Integer studentNo);
18     @Update("update student set studentName=#{studentName} where studentNo=#{studentNo}")
19     public void update(Student student);
20     @Insert("insert into student values(null,#{studentName},#{age},#{boreDate},#{classNo})")
21     public void add(Student student);
22     @Select(" select * from student where studentName like \"%\"#{studentName}\"%\"")
23     public List<Student> findByName(String name);
24 }
dao

12...service

 1 package com.wsc.service;
 2 
 3 import com.wsc.domain.Student;
 4 
 5 import java.util.List;
 6 
 7 public interface StudentService {
 8     public List<Student> findAllStudent();
 9     public Student findById(Integer studentNo);
10     public void drop(Integer studentNo);
11     public void update(Student student);
12     public void add(Student student);
13     public List<Student> findByName(String name);
14 }
service

13...serviceImpl

 1 package com.wsc.service.impl;
 2 
 3 import com.wsc.dao.StudentDao;
 4 import com.wsc.domain.Student;
 5 import com.wsc.service.StudentService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 
 9 import java.util.List;
10 
11 /**
12  * @version 1.0
13  * @ClassName StudentServiceImpl
14  * @Description TODO
15  * @Author WSC
16  * @Date 2019/7/12 13:58
17  **/
18 @Service
19 public class StudentServiceImpl implements StudentService {
20     @Autowired
21     StudentDao studentDao;
22     @Override
23     public List<Student> findAllStudent() {
24         return studentDao.findAllStudent();
25     }
26 
27     @Override
28     public Student findById(Integer studentNo) {
29         return studentDao.findById(studentNo);
30     }
31 
32     @Override
33     public void drop(Integer studentNo) {
34         studentDao.drop(studentNo);
35     }
36 
37     @Override
38     public void update(Student student) {
39         studentDao.update(student);
40     }
41 
42     @Override
43     public void add(Student student) {
44         studentDao.add(student);
45     }
46 
47     @Override
48     public List<Student> findByName(String name) {
49         return studentDao.findByName(name);
50     }
51 }
serviceImpl

14...controller (ModelAndView

 1 package com.wsc.controller;
 2 
 3 import com.wsc.domain.Student;
 4 import com.wsc.service.StudentService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 import java.util.List;
11 
12 /**
13  * @version 1.0
14  * @ClassName StudentController
15  * @Description TODO
16  * @Author WSC
17  * @Date 2019/7/15 11:28
18  **/
19 @Controller
20 @RequestMapping("/student")
21 public class StudentController {
22     @Autowired
23     StudentService studentService;
24     @RequestMapping("/findAll")
25     public ModelAndView findAll(){
26         List<Student> allStudent = studentService.findAllStudent();
27         ModelAndView modelAndView = new ModelAndView();
28         modelAndView.addObject("allStudent",allStudent);
29         modelAndView.setViewName("show");
30         return modelAndView;
31     }
32     @RequestMapping("/drop")
33         public String drop(Integer studentNo){
34             studentService.drop(studentNo);
35             return "redirect:findAll";
36     }
37 
38     @RequestMapping("/add")
39     public String add(Student student){
40         studentService.add(student);
41         return "redirect:findAll";
42     }
43    @RequestMapping("/updatee")
44     public ModelAndView update(Integer studentNo){
45        Student byId = studentService.findById(studentNo);
46        ModelAndView modelAndView = new ModelAndView();
47        modelAndView.addObject("student",byId);
48        modelAndView.setViewName("update");
49        return modelAndView;
50    }
51    @RequestMapping("/update")
52     public String update2(Student student){
53     studentService.update(student);
54        return "redirect:findAll";
55    }
56    }
controller

猜你喜欢

转载自www.cnblogs.com/wangshichang/p/11364785.html
0条评论
添加一条新回复
  
今日推荐