最近閑來無事應(yīng)朋友只需,整理了一下以前學(xué)習(xí)Spring框架和 Mybatis 框架的一些資料,自己寫了一個(gè)小的單表增刪查改的 dome.
在寫之前需要需要下載好Spring的jar包和 Mybatis的 jar包,在 Mysql 建一個(gè) tb_user 的單表.
下面是工程的一個(gè)包結(jié)構(gòu):
db.properties文件內(nèi)容
##oracle 和 mysql 你使用其中一個(gè)即可,根據(jù)自己的賬號密碼填寫
##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
實(shí)體類 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 {
/**
* 新增數(shù)據(jù)
*@param user
*/
int insertUser(User user);
/**
* 更新數(shù)據(jù)
*@param user
*/
int updateUser(User user);
/**
* 刪除數(shù)據(jù)
*@param user
*/
int deleteUser(User user);
/**
* 根據(jù)name 查詢
*@param name
*/
List<User> getUserByName(String name);
}
業(yè)務(wù)層 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);
/**
* 根據(jù)id用戶
*@param name
*/
void dropUser(Integer id);
}
UserServiceImpl是 UserService 的實(shí)現(xiàn)類
@Service // spring容器管理對象 Spring 的注解開發(fā)
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"
>
<!-- 配置文件描述標(biāo)簽 -->
<description>
<![CDATA[
描述內(nèi)容. 配置Spring整合MyBatis技術(shù)中的基礎(chǔ)數(shù)據(jù)
如 : 數(shù)據(jù)源
]]>
</description>
<!-- 使用spring的技術(shù),讀取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>
<!-- 數(shù)據(jù)源, 如果spring容器讀取了properties配置文件內(nèi)容. 那么可以通過springEL表達(dá)式中的${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>
<!-- 數(shù)據(jù)源, 如果不寫配置文件就直接一一對應(yīng)上也行
-->
</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"
>
<!-- 配置文件描述標(biāo)簽 -->
<description>
<![CDATA[
描述內(nèi)容. 配置MyBatis中SqlSessionFactory的配置文件.
]]>
</description>
<!-- 配置SqlSessionFactory. 導(dǎo)入了一個(gè)mybatis-spring-x.x.x.jar
在jar包中,定義了spring和mybatis整合相關(guān)的類型.
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations">
<array>
<!-- 導(dǎo)入目錄cn/sxt/mapper/中的所有xml配置文件. -->
<value>classpath:cn/sxt/mapper/*.xml</value>
</array>
</property>
<property name="typeAliasesPackage">
<value>cn.sxt.entity</value>
</property>
</bean>
<!-- 第二種配置方案
自動(dòng)掃描basePackage中的接口和XML配置文件.實(shí)現(xiàn)動(dòng)態(tài)代理對象的創(chuàng)建.
相當(dāng)于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"
>
<!-- 配置文件描述標(biāo)簽 -->
<description>
<![CDATA[
描述內(nèi)容. 配置掃描Service的標(biāo)簽
]]>
</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"
>
<!-- 配置文件描述標(biāo)簽 -->
<description>
<![CDATA[
描述內(nèi)容. 配置事務(wù)管理,聲明式事務(wù)管理.
]]>
</description>
<!-- 配置一個(gè)事務(wù)管理器.是一個(gè)Spring定義好的java類.
MyBatis是一個(gè)輕量級封裝的框架.封裝的級別比較輕.層次少.對JDBC的封裝少.
MyBatis框架對事務(wù)管理,都是借助JDBC實(shí)現(xiàn)的.
使用的事務(wù)管理器,就是DataSourceTransactionManager.
-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定義一套通知,實(shí)現(xiàn)事務(wù)的細(xì)粒度管理. -->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<!-- 配置事務(wù)管理通知屬性. -->
<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">
<!-- 增加一個(gè)新的屬性.可選屬性.
parameterType - 可選屬性. 用來明確定義,當(dāng)前方法的輸入?yún)?shù)具體類型是什么.
常用配置為 : 自定義類型,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>
<!-- 更新數(shù)據(jù) -->
<update id="updateUser">
update tb_user
<!-- set標(biāo)簽. 動(dòng)態(tài)設(shè)置set語法結(jié)構(gòu).可以自動(dòng)刪除最后一個(gè)逗號.類似where標(biāo)簽的功能. -->
<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>
<!-- 刪除數(shù)據(jù) -->
<delete id="deleteUser">
delete from tb_user
where id = #{id}
</delete>
<!-- 同構(gòu) id 查找數(shù)據(jù) -->
<select id="getUserByName" resultType="User">
select id, name, password, age
from tb_user
where name = #{name}
</select>
</mapper>
接下來我們做測試,建一個(gè)測試類,到如一個(gè) JUnit jar包
也可以用 main 做測試也行,測試就不詳細(xì)說了.看代碼.
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());
}
}