spring 整合 mybatis 及mybatis 的 crud 操作

君墨痕發表於2013-09-27

今天有空學習了一下mybatis,這個orm框架和jdbctemplate很相似,都需要自己寫sql語句,都可以對sql進行優化控制。有點不同的mybatis不需要再一個mapper的實體來對映結果集,只需要配置是指定一下實體物件即可,它會自動幫你對映到該實體上;而jdbctemplate則需要自己另外寫一個實現rowmapper藉口的結果集對映物件。

還有其他的mybatis詳細使用方法可以去官網看看,我這裡貼下spring 整合mybatis及簡單的crud操作的程式碼。

mybatis學習的傳送門:http://mybatis.github.io/mybatis-3/zh/dynamic-sql.html


spring的配置檔案applicationContext.xml,配置資料來源和mybatis的sqlSessionFactory,

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="maxActive" value="${jdbc.maxActive}"></property>
		<property name="maxIdle" value="${jdbc.maxIdle}"></property>
		<property name="maxWait" value="${jdbc.maxWait}"></property>
		<property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"></property>
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:configuration.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

configuration.xm

<?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>
		<!--給實體類起一個別名 user ,userMapper.xml中的就可以這樣定義resultType="User" -->
		<!--就無需這樣寫路徑了 resultType="com.forum.po.User" -->
		<typeAlias type="com.yang.model.User" alias="User" />
		<typeAlias type="com.yang.model.Books" alias="Books" />
	</typeAliases>

	<mappers>
		<!--userMapper.xml裝載進來 同等於把“dao”的實現裝載進來 -->
		<mapper resource="com/yang/dao/impl/userMapper.xml" />
		<mapper resource="com/yang/dao/impl/bookMapper.xml" />
	</mappers>

</configuration> 


bookMapper.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">

<!--這塊等於dao介面的實現 namespace必須和介面的類路徑一樣 -->
<mapper namespace="com.yang.dao.BookMapper">

	<!-- id必須和介面中的方法名一樣 返回一個Books 就是剛才的別名 如果不弄別名要連類路徑一起寫 麻煩 -->
	<select id="findById" parameterType="int" resultType="Books">
		select
		*
		from books where book_id=#{book_id}
	</select>

	<select id="findByName" parameterType="string" resultType="Books">
		select
		*
		from books where book_name like #{book_name}
	</select>

	<insert id="save" parameterType="Books" useGeneratedKeys="true"
		keyProperty="book_id">
		insert into books(book_name,book_author,book_date)
		values(#{book_name},#{book_author},#{book_date})
	</insert>

	<update id="update" parameterType="Books">
		update books set
		book_name=#{book_name},book_author=#{book_author},book_date=#{book_date}
		where book_id=#{book_id}
	</update>

	<delete id="delete" parameterType="int">
		delete from books where
		book_id=#{book_id}
	</delete>

	<select id="findByArgs" parameterType="map" resultType="Books">
		select
		*
		from books where book_name like #{book_name}
		<if test="book_publish!=null">
			and book_publish like #{book_publish}
		</if>
	</select>
	
</mapper>

com.yang.dao.BookMapper,dao介面,上面的mapper是這個dao介面的實現

public interface BookMapper {

	public Books findById(int book_id);

	public List<Books> findByName(String book_name);

	public int save(Books books);

	public int update(Books books);

	public int delete(int book_id);

	public List<Books> findByArgs(Map<String, String> map);
}

service層的介面

public interface IBookService {

	public Books findById(int book_id);

	public List<Books> findByName(String book_name);

	public int save(Books books);

	public int update(Books books);

	public int delete(int book_id);
	
	public List<Books> findByArgs(Map<String, String> map);

	public void testTransaction(Books books, int deleteId);

}

service層的實現

public class BookServiceImpl implements IBookService {

	private BookMapper bookMapper;

	public void setBookMapper(BookMapper bookMapper) {
		this.bookMapper = bookMapper;
	}

	public Books findById(int book_id) {
		return this.bookMapper.findById(book_id);
	}

	public List<Books> findByName(String book_name) {
		return this.bookMapper.findByName(book_name);
	}

	public int save(Books books) {
		return this.bookMapper.save(books);
	}

	public int update(Books books) {
		return this.bookMapper.update(books);
	}

	public int delete(int book_id) {
		return this.bookMapper.delete(book_id);
	}

	public List<Books> findByArgs(Map<String, String> map) {
		return this.bookMapper.findByArgs(map);
	}

	public void testTransaction(Books books, int deleteId) {
		this.bookMapper.save(books);
		this.bookMapper.delete(deleteId);
		throw new RuntimeException(" ------- 事務測試");
	}

}

上面的實現類裡需要在spring配置檔案中注入bookMapper

	<bean id="bookService" class="com.yang.service.impl.BookServiceImpl">
		<property name="bookMapper" ref="bookMapper" />
	</bean>

bookMapper配置

<bean id="bookMapper" class="org.mybatis.spring.MapperFactoryBean">
		<property name="mapperInterface" value="com.yang.dao.BookMapper" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>


最後junit單元測試一下

	private ApplicationContext applicationContext;
	private IUserService userService;
	private IBookService bookService;

	@Before
	public void before() {
		String[] xmls = new String[] { "applicationContext.xml",
				"applicationContext-mapper.xml",
				"applicationContext-service.xml",
				"applicationContext-transaction.xml" };
		applicationContext = new ClassPathXmlApplicationContext(xmls);
		userService = (IUserService) applicationContext.getBean("userService");
		bookService = (IBookService) applicationContext.getBean("bookService");
	}


	@Test
	public void findByArgs() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("book_name", "%bbb%");
		map.put("book_publish", null);
		List<Books> books = this.bookService.findByArgs(map);
		for (Books b : books) {
			System.out.println(b.getBook_id() + " --- " + b.getBook_name()
					+ " --- " + b.getBook_publish() + " --- "
					+ b.getBook_date());
		}
	}


結果:


也附上目錄結構


相關文章