MyBatis集成Spring開發 講解
來源:程序員人生 發布時間:2015-05-29 08:16:23 閱讀次數:3267次
MyBatis集成Spring開發 講授
簡介:Spring集成Mybatis開發簡述有兩種方式,第1種是在applicationContext.xml中配置接口掃描類(同時也掃描了sql.xml配置文件)或注入接口類(MapperScannerConfigurer、MapperFactoryBean這兩個在test中有講授如何配置),第2種是原生的Mybatis,不用接口開發,而在applicationContext.xml中當配置sqlSessionFactory時候,配置如conf.xml文件,讓Mybatis自己掃描,從而在程序中使用原生Mybatis做CRUD操作。
注意點,在上1篇文章中寫到了Mybatis的注解方式也是接口,在spring中的接口和注解方式是不1樣的,注解方式的時候定義了接口,要在接口中寫入配置,比如@Select("select * from Users where
id = #{id}")等,不需要對應的sql.xml配置文件,2在Spring中,寫入了接口,還需要對應的sql.xml配置文件,而這個文件的namespace就是對應的接口全名,使用MapperScannerConfigurer掃描了接口類型后,在調用的時候使用接口類型.save()等方法來實現CRUD。
1、項目清單

2、順序源碼
package com.bjsxt.bean;
public class User {
//shift+alt+s
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
package com.bjsxt.user.dao;
import java.util.List;
import com.bjsxt.bean.User;
public interface UserMapper {
void save(User user);
void update(User user);
void delete(int id);
User findById(int id);
List<User> findAll();
}
package com.bjsxt.user.dao;
import java.util.List;
import com.bjsxt.bean.User;
public interface UserMapper2 {
void save(User user);
void update(User user);
void delete(int id);
User findById(int id);
List<User> findAll();
}
<?xml version="1.0" encoding="UTF⑻"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis⑶-mapper.dtd">
<!-- spring集成Mybatis namespace 必須是接口的全類名 -->
<mapper namespace="com.bjsxt.user.dao.UserMapper">
<insert id="save" parameterType="User" >
insert into users(name,age) values(#{name},#{age})
</insert>
</mapper>
<?xml version="1.0" encoding="UTF⑻"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis⑶-mapper.dtd">
<!-- spring集成Mybatis namespace 必須是接口的全類名 -->
<mapper namespace="com.bjsxt.user.dao.UserMapper2">
<insert id="save" parameterType="User" >
insert into users(name,age) values(#{name},#{age})
</insert>
</mapper>
package com.test;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.bjsxt.bean.User;
import com.bjsxt.user.dao.UserMapper;
import com.bjsxt.user.dao.UserMapper2;
/**
* 配置了這個,<bean
* class="org.mybatis.spring.mapper.MapperScannerConfigurer">,就不在需要配置
* org.mybatis.spring.mapper.MapperFactoryBean了.前者配置1次,自動注入不同的接口類就能夠了
* 后者也是通過封裝成了單個前者,而且還需要配置多個,所以用前者自動掃面,所有的接口和sql配置文件
* ,在下面的測試類中注入1個接口類,配置的MapperScannerConfigurer會自動的
* 解析出所有的接口提供方法的使用,MapperScannerConfigurer不用配置id了,沒有甚么意義了
*
*
*/
@Component
public class Test {
@Autowired
private UserMapper userMapper;
@Autowired
private UserMapper2 userMapper2;
/**
* 下面兩個是測試不同的接口類的實現
*/
@org.junit.Test
public void saveUser1() {
ApplicationContext ac = new ClassPathXmlApplicationContext(
"applicationContext.xml");
SqlSessionFactory sf = (SqlSessionFactory) ac
.getBean("sqlSessionFactory");
SqlSession session = sf.openSession();
Test t = (Test) ac.getBean("test");
System.out.println(t.userMapper);
t.userMapper.save(new User(⑴, "連發2", 1));
}
@org.junit.Test
public void saveUser2() {
ApplicationContext ac = new ClassPathXmlApplicationContext(
"applicationContext.xml");
SqlSessionFactory sf = (SqlSessionFactory) ac
.getBean("sqlSessionFactory");
SqlSession session = sf.openSession();
Test t = (Test) ac.getBean("test");
System.out.println(t.userMapper2);
t.userMapper2.save(new User(⑴, "連發2", 1));
}
/**
* application.xml mybatis.spring.mapper.MapperFactoryBean 配置的實現與測試
* 如果有多個接口那末久需要屢次這樣的配置,根據id來辨認具體的接口類型
*/
@org.junit.Test
public void saveUser3() {
ApplicationContext ac = new ClassPathXmlApplicationContext(
"applicationContext.xml");
SqlSessionFactory sf = (SqlSessionFactory) ac
.getBean("sqlSessionFactory");
SqlSession session = sf.openSession();
UserMapper mapper = (UserMapper) ac.getBean("UserMapper");
mapper.save(new User(⑴, "連發3", 1));
}
/**
* application.xml中引入了conf.xml配置文件的測試
*/
@org.junit.Test
public void saveUser4() {
ApplicationContext ac = new ClassPathXmlApplicationContext(
"applicationContext.xml");
SqlSessionFactory sf = (SqlSessionFactory) ac
.getBean("sqlSessionFactory");
SqlSession session = sf.openSession(true);
session.insert("com.bjsxt.user.dao.UserMapper.save",new User(⑴, "老婆", 27));
}
public static void main(String[] args) {
new Test().saveUser4();
}
}
3、applicationContext.xml 配置講授
<?xml version="1.0" encoding="UTF⑻"?>
<beans
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans⑶.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context⑶.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx⑶.2.xsd"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<context:component-scan base-package="com"></context:component-scan>
<!-- 1. 數據源 : DriverManagerDataSource -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="datasource">
<property value="com.mysql.jdbc.Driver" name="driverClassName" />
<property value="jdbc:mysql://localhost:3306/mybaits" name="url" />
<property value="root" name="username" />
<property value="123456" name="password" />
</bean>
<!--
2. mybatis的SqlSession的工廠: SqlSessionFactoryBean dataSource /
typeAliasesPackage
-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="dataSource" ref="datasource" />
<property value="com.bjsxt.bean" name="typeAliasesPackage" />
<!--configLocation屬性指定mybatis的核心配置文件-->
<property name="configLocation" value="conf.xml"/>
</bean>
<!--
3. mybatis自動掃描加載Sql映照文件和接口
通過類型的注入就能夠直接使用其中的方法
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property value="com.bjsxt.user.dao" name="basePackage" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 專門配置兩個接口Mapper 下面兩個配置就是,但是這類方式是比較不適用的,要用的話呢就在上面自動掃描的配置中進行 -->
<bean id="UserMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.bjsxt.user.dao.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="UserMapper2" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.bjsxt.user.dao.UserMapper2"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<!-- 4. 事務管理 : DataSourceTransactionManager -->
<bean
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
id="manager">
<property name="dataSource" ref="datasource" />
</bean>
<!-- 5. 使用聲明式事務 -->
<tx:annotation-driven transaction-manager="manager" />
</beans>
4、conf.xml 配置講授
<?xml version="1.0" encoding="UTF⑻"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis⑶-config.dtd">
<configuration>
<!-- 配置實體類的別名 -->
<typeAliases>
<!-- 下面二者前者是別名,后者是讓在xml中省去了包名的寫,可直接寫入簡單類名就好了 -->
<typeAlias type="com.bjsxt.bean.User" alias="_User"/>
<package name="com.bjsxt.bean"/>
</typeAliases>
<!--
development : 開發模式
work : 工作模式
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybaits" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/bjsxt/user/dao/userMapper.xml"/>
<mapper resource="com/bjsxt/user/dao/userMapper2.xml"/>
</mappers>
</configuration>
5、lib 下載地址
Spring集成Mybatis需要的包
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈