• Java基础-SSM之Spring和Mybatis整合案例


                    Java基础-SSM之Spring和Mybatis整合案例

                                             作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

       在之前我分享过mybatis和Spring的配置案例,想必大家对它们的配置已经很熟悉了,接下来我们把两者结合起来让他们一起来协同工作,帮我们在数据库中插入数据,编程起来是相当的方便。

    一.准备环境

    1>.案例分析

       我们想要把一条数据插入到数据库中,利用Spring和mybatis插件来完成,大致的流程图如下:

    2>.数据库配置创建测试数据表 

      在编程之前,我们需要启动数据库,并在数据库中提前创建出我们需要用到的测试表。创建过程如下:

    1 create database yinzhengjie;
    2 
    3 use yinzhengjie;
    4 
    5 create table if not exists users(id int primary key auto_increment,name varchar(20) , age int) ;

    二.实操演示

    1>.创建新模块,引入Maven依赖

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3          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>cn.org.yinzhengjie</groupId>
     8     <artifactId>MySpringMybatis</artifactId>
     9     <version>1.0-SNAPSHOT</version>
    10 
    11     <dependencies>
    12         <dependency>
    13             <groupId>junit</groupId>
    14             <artifactId>junit</artifactId>
    15             <version>4.11</version>
    16         </dependency>
    17         <dependency>
    18             <groupId>org.springframework</groupId>
    19             <artifactId>spring-context-support</artifactId>
    20             <version>4.3.5.RELEASE</version>
    21         </dependency>
    22         <dependency>
    23             <groupId>org.springframework</groupId>
    24             <artifactId>spring-jdbc</artifactId>
    25             <version>4.3.5.RELEASE</version>
    26         </dependency>
    27         <dependency>
    28             <groupId>org.mybatis</groupId>
    29             <artifactId>mybatis</artifactId>
    30             <version>3.2.1</version>
    31         </dependency>
    32         <dependency>
    33             <groupId>org.mybatis</groupId>
    34             <artifactId>mybatis-spring</artifactId>
    35             <version>1.3.0</version>
    36         </dependency>
    37         <dependency>
    38             <groupId>c3p0</groupId>
    39             <artifactId>c3p0</artifactId>
    40             <version>0.9.1.2</version>
    41         </dependency>
    42         <dependency>
    43             <groupId>mysql</groupId>
    44             <artifactId>mysql-connector-java</artifactId>
    45             <version>5.1.17</version>
    46         </dependency>
    47         <dependency>
    48             <groupId>org.aspectj</groupId>
    49             <artifactId>aspectjrt</artifactId>
    50             <version>1.6.1</version>
    51         </dependency>
    52         <dependency>
    53             <groupId>org.aspectj</groupId>
    54             <artifactId>aspectjweaver</artifactId>
    55             <version>1.8.10</version>
    56         </dependency>
    57     </dependencies>
    58 </project>

    2>.创建相应的包并编写代码

     

     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 package cn.org.yinzhengjie.sm.dao;
     7 
     8 import java.util.List;
     9 
    10 /**
    11  * Basedao,基本dao
    12  */
    13 public interface BaseDao<T> {
    14     public void insert(T t) ;
    15     public void update(T t) ;
    16     public void delete(Integer id) ;
    17     public T selectOne(Integer id) ;
    18     public List<T> selectAll() ;
    19 }
    BaseDao.java 文件内容
     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 package cn.org.yinzhengjie.sm.dao.impl;
     7 
     8 import cn.org.yinzhengjie.sm.dao.BaseDao;
     9 import cn.org.yinzhengjie.sm.domain.User;
    10 import org.apache.ibatis.session.SqlSessionFactory;
    11 import org.mybatis.spring.support.SqlSessionDaoSupport;
    12 import org.springframework.stereotype.Repository;
    13 
    14 import javax.annotation.Resource;
    15 import java.util.List;
    16 
    17 /**
    18  *
    19  */
    20 @Repository("userDao")
    21 public class UserDaoImpl extends SqlSessionDaoSupport implements BaseDao<User> {
    22 
    23     public void insert(User user) {
    24         getSqlSession().insert("users.insert" , user) ;
    25     }
    26 
    27     public void update(User user) {
    28         getSqlSession().update("users.update", user);
    29     }
    30 
    31     public void delete(Integer id) {
    32         getSqlSession().delete("users.deleteOne", id);
    33     }
    34 
    35     public User selectOne(Integer id) {
    36         return getSqlSession().selectOne("users.selectOne", id);
    37     }
    38 
    39     public List<User> selectAll() {
    40         return getSqlSession().selectList("users.selectAll");
    41     }
    42 
    43     @Resource(name="sqlSessionFactory")
    44     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    45         super.setSqlSessionFactory(sqlSessionFactory);
    46     }
    47 }
    UserDaoImpl.java 文件内容
     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 package cn.org.yinzhengjie.sm.service;
     7 
     8 import java.util.List;
     9 
    10 /**
    11  * Created by Administrator on 2018/7/12.
    12  */
    13 public interface BaseService<T> {
    14     public void insert(T t);
    15 
    16     public void update(T t);
    17 
    18     public void delete(Integer id);
    19 
    20     public T selectOne(Integer id);
    21 
    22     public List<T> selectAll();
    23 }
    BaseService.java 文件内容
     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 package cn.org.yinzhengjie.sm.service.impl;
     7 
     8 import cn.org.yinzhengjie.sm.dao.BaseDao;
     9 import cn.org.yinzhengjie.sm.domain.User;
    10 import cn.org.yinzhengjie.sm.service.BaseService;
    11 import org.springframework.stereotype.Service;
    12 
    13 import javax.annotation.Resource;
    14 import java.util.List;
    15 
    16 /**
    17  * 用户服务实现类
    18  */
    19 @Service("userService")
    20 public class UserServiceImpl implements BaseService<User> {
    21 
    22     @Resource(name="userDao")
    23     private BaseDao<User> userDao ;
    24 
    25     public void insert(User user) {
    26         userDao.insert(user);
    27     }
    28 
    29     public void update(User user) {
    30         userDao.update(user);
    31     }
    32 
    33     public void delete(Integer id) {
    34         userDao.delete(id);
    35     }
    36 
    37     public User selectOne(Integer id) {
    38         return userDao.selectOne(id);
    39     }
    40 
    41     public List<User> selectAll() {
    42         return userDao.selectAll();
    43     }
    44 }
    UserServiceImpl.java 文件内容
     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 package cn.org.yinzhengjie.sm.domain;
     7 
     8 /**
     9  */
    10 public class User {
    11     private Integer id;
    12     private String name;
    13     private int age;
    14 
    15     public Integer getId() {
    16         return id;
    17     }
    18 
    19     public void setId(Integer id) {
    20         this.id = id;
    21     }
    22 
    23     public String getName() {
    24         return name;
    25     }
    26 
    27     public void setName(String name) {
    28         this.name = name;
    29     }
    30 
    31     public int getAge() {
    32         return age;
    33     }
    34 
    35     public void setAge(int age) {
    36         this.age = age;
    37     }
    38 }
    User.java 文件内容

    3>.编写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 <configuration>
     6     <typeAliases>
     7         <typeAlias type="cn.org.yinzhengjie.sm.domain.User"    alias="_User" />
     8     </typeAliases>
     9     <mappers>
    10         <mapper resource="UserMapper.xml"/>
    11     </mappers>
    12 </configuration>
    mybatis-config.xml 文件内容
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     3         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     4 <!-- 定义名字空间 -->
     5 <mapper namespace="users">
     6     <insert id="insert">
     7         insert into users(name, age) values(#{name}, #{age}) ;
     8     </insert>
     9 
    10     <update id="update">
    11         update users set name = #{name} , age = #{age} where id = #{id}
    12     </update>
    13 
    14     <delete id="deleteOne">
    15         delete from users where id = #{id}
    16     </delete>
    17 
    18     <select id="selectOne" resultType="_User">
    19         select * from users where id = #{id}
    20     </select>
    21 
    22     <select id="selectAll" resultType="_User">
    23         select * from users
    24     </select>
    25 
    26 </mapper>
    UserMapper.xml 文件内容

    4>.编写Spring的配置文件(环绕通知,文件名为:beans.xml)

     1 <?xml version="1.0"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xmlns:aop="http://www.springframework.org/schema/aop"
     5        xmlns:context="http://www.springframework.org/schema/context"
     6        xmlns:tx="http://www.springframework.org/schema/tx"
     7        xsi:schemaLocation="http://www.springframework.org/schema/beans
     8                         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
     9                         http://www.springframework.org/schema/aop
    10                         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    11                         http://www.springframework.org/schema/context
    12                         http://www.springframework.org/schema/context/spring-context-4.3.xsd
    13                         http://www.springframework.org/schema/tx
    14                         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    15     <context:component-scan base-package="cn.org.yinzhengjie.sm.service,cn.org.yinzhengjie.sm.dao" />
    16     <!-- 数据源 -->
    17     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    18         <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    19         <property name="jdbcUrl" value="jdbc:mysql://localhost:5200/yinzhengjie"/>
    20         <property name="user" value="root"/>
    21         <property name="password" value="yinzhengjie"/>
    22         <property name="maxPoolSize" value="10"/>
    23         <property name="minPoolSize" value="2"/>
    24         <property name="initialPoolSize" value="3"/>
    25         <property name="acquireIncrement" value="2"/>
    26     </bean>
    27 
    28     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    29         <property name="dataSource" ref="dataSource"/>
    30         <property name="configLocation" value="classpath:mybatis-config.xml"/>
    31     </bean>
    32 
    33     <!-- 事务管理器,在servie层面上实现事务管理的。 -->
    34     <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    35         <property name="dataSource" ref="dataSource" />
    36     </bean>
    37 
    38     <!-- 事务通知 -->
    39     <tx:advice id="txAdvicd" transaction-manager="txManager">
    40         <tx:attributes>
    41             <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" />
    42             <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" />
    43             <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" />
    44             <tx:method name="select*" propagation="REQUIRED" isolation="DEFAULT" read-only="true" />
    45             <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" />
    46         </tx:attributes>
    47     </tx:advice>
    48 
    49     <!-- 定义环绕通知 -->
    50     <aop:config>
    51         <aop:advisor pointcut="execution(* *..*Service.*(..))" advice-ref="txAdvicd" />
    52     </aop:config>
    53 </beans>

    5>.新建包名(cn.org.yinzhengjie.sm.main), 编写测试代码如下:

     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 package cn.org.yinzhengjie.sm.main;
     7 
     8 import cn.org.yinzhengjie.sm.domain.User;
     9 import cn.org.yinzhengjie.sm.service.BaseService;
    10 import org.springframework.context.ApplicationContext;
    11 import org.springframework.context.support.ClassPathXmlApplicationContext;
    12 
    13 public class Demo {
    14     public static void main(String[] args) {
    15         ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    16         BaseService service = (BaseService) ac.getBean("userService");
    17         User user = new User();
    18         user.setName("YinZhengJie");
    19         user.setAge(18);
    20         service.insert(user);
    21 
    22         User yzj = (User)service.selectOne(1);
    23         System.out.println(yzj.getName());
    24     }
    25 }

      以上代码执行结果如下:

    6>.运行第5步的测试代码,并查看数据库信息:

     

  • 相关阅读:
    机器学习框架ML.NET学习笔记【5】多元分类之手写数字识别(续)
    机器学习框架ML.NET学习笔记【3】文本特征分析
    机器学习框架ML.NET学习笔记【2】入门之二元分类
    Git项目下载部分文件或文件夹
    一个扫雷游戏和一个自动玩扫雷游戏的程序
    循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密
    循序渐进学.Net Core Web Api开发系列【15】:应用安全
    循序渐进学.Net Core Web Api开发系列【14】:异常处理
    通过源码学习@functools.lru_cache
    【Python3爬虫】破解时光网登录加密参数并实现模拟登录
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/9298084.html
Copyright © 2020-2023  润新知