Java基础-SSM之Spring和Mybatis整合案例
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
在之前我分享过mybatis和Spring的配置案例,想必大家对它们的配置已经很熟悉了,接下来我们把两者结合起来让他们一起来协同工作,帮我们在数据库中插入数据,编程起来是相当的方便。
一.准备环境
1>.案例分析
我们想要把一条数据插入到数据库中,利用Spring和mybatis插件来完成,大致的流程图如下:
2>.数据库配置创建测试数据表
在编程之前,我们需要启动数据库,并在数据库中提前创建出我们需要用到的测试表。创建过程如下:
create database yinzhengjie; use yinzhengjie; create table if not exists users(id int primary key auto_increment,name varchar(20) , age int) ;
二.实操演示
1>.创建新模块,引入Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cn.org.yinzhengjie</groupId>
<artifactId>MySpringMybatis</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
</dependencies>
</project>
2>.创建相应的包并编写代码
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.sm.dao; import java.util.List; /**
* Basedao,基本dao
*/
public interface BaseDao<T> {
public void insert(T t) ;
public void update(T t) ;
public void delete(Integer id) ;
public T selectOne(Integer id) ;
public List<T> selectAll() ;
}
BaseDao.java 文件内容
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.sm.dao.impl; import cn.org.yinzhengjie.sm.dao.BaseDao;
import cn.org.yinzhengjie.sm.domain.User;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository; import javax.annotation.Resource;
import java.util.List; /**
*
*/
@Repository("userDao")
public class UserDaoImpl extends SqlSessionDaoSupport implements BaseDao<User> { public void insert(User user) {
getSqlSession().insert("users.insert" , user) ;
} public void update(User user) {
getSqlSession().update("users.update", user);
} public void delete(Integer id) {
getSqlSession().delete("users.deleteOne", id);
} public User selectOne(Integer id) {
return getSqlSession().selectOne("users.selectOne", id);
} public List<User> selectAll() {
return getSqlSession().selectList("users.selectAll");
} @Resource(name="sqlSessionFactory")
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
}
UserDaoImpl.java 文件内容
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.sm.service; import java.util.List; /**
* Created by Administrator on 2018/7/12.
*/
public interface BaseService<T> {
public void insert(T t); public void update(T t); public void delete(Integer id); public T selectOne(Integer id); public List<T> selectAll();
}
BaseService.java 文件内容
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.sm.service.impl; import cn.org.yinzhengjie.sm.dao.BaseDao;
import cn.org.yinzhengjie.sm.domain.User;
import cn.org.yinzhengjie.sm.service.BaseService;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.util.List; /**
* 用户服务实现类
*/
@Service("userService")
public class UserServiceImpl implements BaseService<User> { @Resource(name="userDao")
private BaseDao<User> userDao ; public void insert(User user) {
userDao.insert(user);
} public void update(User user) {
userDao.update(user);
} public void delete(Integer id) {
userDao.delete(id);
} public User selectOne(Integer id) {
return userDao.selectOne(id);
} public List<User> selectAll() {
return userDao.selectAll();
}
}
UserServiceImpl.java 文件内容
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.sm.domain; /**
*/
public class User {
private Integer id;
private String name;
private int 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 int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}
User.java 文件内容
3>.编写mybatis的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="cn.org.yinzhengjie.sm.domain.User" alias="_User" />
</typeAliases>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
mybatis-config.xml 文件内容
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 定义名字空间 -->
<mapper namespace="users">
<insert id="insert">
insert into users(name, age) values(#{name}, #{age}) ;
</insert> <update id="update">
update users set name = #{name} , age = #{age} where id = #{id}
</update> <delete id="deleteOne">
delete from users where id = #{id}
</delete> <select id="selectOne" resultType="_User">
select * from users where id = #{id}
</select> <select id="selectAll" resultType="_User">
select * from users
</select> </mapper>
UserMapper.xml 文件内容
4>.编写Spring的配置文件(环绕通知,文件名为:beans.xml)
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="cn.org.yinzhengjie.sm.service,cn.org.yinzhengjie.sm.dao" />
<!-- 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:5200/yinzhengjie"/>
<property name="user" value="root"/>
<property name="password" value="yinzhengjie"/>
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="2"/>
<property name="initialPoolSize" value="3"/>
<property name="acquireIncrement" value="2"/>
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean> <!-- 事务管理器,在servie层面上实现事务管理的。 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 事务通知 -->
<tx:advice id="txAdvicd" transaction-manager="txManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" />
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" />
<tx:method name="select*" propagation="REQUIRED" isolation="DEFAULT" read-only="true" />
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" />
</tx:attributes>
</tx:advice> <!-- 定义环绕通知 -->
<aop:config>
<aop:advisor pointcut="execution(* *..*Service.*(..))" advice-ref="txAdvicd" />
</aop:config>
</beans>
5>.新建包名(cn.org.yinzhengjie.sm.main), 编写测试代码如下:
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.sm.main; import cn.org.yinzhengjie.sm.domain.User;
import cn.org.yinzhengjie.sm.service.BaseService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Demo {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
BaseService service = (BaseService) ac.getBean("userService");
User user = new User();
user.setName("YinZhengJie");
user.setAge(18);
service.insert(user); User yzj = (User)service.selectOne(1);
System.out.println(yzj.getName());
}
}
以上代码执行结果如下:
6>.运行第5步的测试代码,并查看数据库信息: