最近闲来无事应朋友只需,整理了一下以前学习Spring框架和 Mybatis 框架的一些资料,自己写了一个小的单表增删查改的 dome.
在写之前需要需要下载好Spring的jar包和 Mybatis的 jar包,在 Mysql 建一个 tb_user 的单表.
下面是工程的一个包结构:
db.properties文件内容
##oracle 和 mysql 你使用其中一个即可,根据自己的账号密码填写
##oracle
##url=jdbc:oracle:thin:@localhost:1521:orcl
##user=scott
##pwd=12345
##driver=oracle.jdbc.OracleDriver
##mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pwd=root
实体类 User类
public class User {
private Integer id;
private String name;
private String password;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Usermapper接口类
public interface UserMapper {
/**
* 新增数据
*@param user
*/
int insertUser(User user);
/**
* 更新数据
*@param user
*/
int updateUser(User user);
/**
* 删除数据
*@param user
*/
int deleteUser(User user);
/**
* 根据name 查询
*@param name
*/
List<User> getUserByName(String name);
}
业务层 service 的 UserService 接口
public interface UserService {
/**
*注册
*@param name
*/
public void register(User user);
/**
* 通过姓名查询用户
*@param name
*/
public List<User> getUserByName(String name);
/**
* 修改用户
*@param name
*/
void modifyUser(User user);
/**
* 根据id用户
*@param name
*/
void dropUser(Integer id);
}
UserServiceImpl是 UserService 的实现类
@Service // spring容器管理对象 Spring 的注解开发
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void register(User user) {
userMapper.insertUser(user);
}
@Override
public List<User> getUserByName(String name) {
return this.userMapper.getUserByName(name);
}
@Override
public void modifyUser(User user) {
this.userMapper.updateUser(user);
}
@Override
public void dropUser(Integer id) {
User user = new User();
user.setId(id);
this.userMapper.deleteUser(user);
}
}
applicationContext-base.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- 配置文件描述标签 -->
<description>
<![CDATA[
描述内容. 配置Spring整合MyBatis技术中的基础数据
如 : 数据源
]]>
</description>
<!-- 使用spring的技术,读取properties配置文件. -->
<bean id="placeholder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:cn/sxt/config/commons/db.properties</value>
</array>
</property>
</bean>
<!-- 数据源, 如果spring容器读取了properties配置文件内容. 那么可以通过springEL表达式中的${key}
访问properties配置文件的value
-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${pwd}" />
</bean>
<!-- 数据源, 如果不写配置文件就直接一一对应上也行
-->
</beans>
applicationContext-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- 配置文件描述标签 -->
<description>
<![CDATA[
描述内容. 配置MyBatis中SqlSessionFactory的配置文件.
]]>
</description>
<!-- 配置SqlSessionFactory. 导入了一个mybatis-spring-x.x.x.jar
在jar包中,定义了spring和mybatis整合相关的类型.
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations">
<array>
<!-- 导入目录cn/sxt/mapper/中的所有xml配置文件. -->
<value>classpath:cn/sxt/mapper/*.xml</value>
</array>
</property>
<property name="typeAliasesPackage">
<value>cn.sxt.entity</value>
</property>
</bean>
<!-- 第二种配置方案
自动扫描basePackage中的接口和XML配置文件.实现动态代理对象的创建.
相当于MapperFactoryBean的简写.
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.sxt.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 第一种配置方案 -->
<!-- <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
abstract="true" lazy-init="true">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="userMapper" parent="baseMapper">
<property name="mapperInterface" value="cn.sxt.mapper.UserMapper" />
</bean> -->
</beans>
applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- 配置文件描述标签 -->
<description>
<![CDATA[
描述内容. 配置扫描Service的标签
]]>
</description>
<!-- 扫描包 -->
<context:component-scan base-package="cn.sxt.service" />
</beans>
applicationContext-tx.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
>
<!-- 配置文件描述标签 -->
<description>
<![CDATA[
描述内容. 配置事务管理,声明式事务管理.
]]>
</description>
<!-- 配置一个事务管理器.是一个Spring定义好的java类.
MyBatis是一个轻量级封装的框架.封装的级别比较轻.层次少.对JDBC的封装少.
MyBatis框架对事务管理,都是借助JDBC实现的.
使用的事务管理器,就是DataSourceTransactionManager.
-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义一套通知,实现事务的细粒度管理. -->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<!-- 配置事务管理通知属性. -->
<tx:attributes>
<tx:method name="register" isolation="DEFAULT" propagation="REQUIRED"
rollback-for="java.lang.Exception"/>
<tx:method name="getUserByName" read-only="true"/>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED"
rollback-for="java.lang.Exception"/>
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED"
rollback-for="java.lang.Exception"/>
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED"
rollback-for="java.lang.Exception"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED"
rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* cn.sxt.service.*.*(..))"/>
</aop:config>
</beans>
UserMapper.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="cn.sxt.mapper.UserMapper">
<!-- 增加一个新的属性.可选属性.
parameterType - 可选属性. 用来明确定义,当前方法的输入参数具体类型是什么.
常用配置为 : 自定义类型,Map集合类型,简单类型.
-->
<insert id="insertUser" parameterType="cn.sxt.entity.User">
insert into tb_user (id, name, password, age)
values(seq_user.nextVal, #{name}, #{password}, #{age})
</insert>
<!-- 更新数据 -->
<update id="updateUser">
update tb_user
<!-- set标签. 动态设置set语法结构.可以自动删除最后一个逗号.类似where标签的功能. -->
<set>
<if test="name != null">
name = #{name},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="age != 0">
age = #{age},
</if>
</set>
<where>
<if test="id != null">
and id = #{id}
</if>
</where>
</update>
<!-- 删除数据 -->
<delete id="deleteUser">
delete from tb_user
where id = #{id}
</delete>
<!-- 同构 id 查找数据 -->
<select id="getUserByName" resultType="User">
select id, name, password, age
from tb_user
where name = #{name}
</select>
</mapper>
接下来我们做测试,建一个测试类,到如一个 JUnit jar包
也可以用 main 做测试也行,测试就不详细说了.看代码.
public class TestSpringMyBatis {
@Test
public void testUpdate(){
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:cn/lx/configurations/spring/applicationContext-*.xml");
UserService userService = context.getBean(UserService.class);
User user = new User();
user.setId(3);
user.setName("老宋");
userService.modifyUser(user);
}
@Test
public void testInsert(){
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:cn/lx/configurations/spring/applicationContext-*.xml");
UserService userService = context.getBean(UserService.class);
User user = new User();
user.setName("天王");
user.setPassword("xoxo");
user.setAge(18);
userService.register(user);
}
@Test
public void testService(){
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:cn/lx/configurations/spring/applicationContext-*.xml");
UserService userService = context.getBean(UserService.class);
System.out.println(userService.getClass().getName());
List<User> users = userService.getUserByName("老王");
for(User u : users){
System.out.println(u.getId() + " ; " + u.getName());
}
}