Spring2.5(全注解)+Ibatis2.3的集成
网址:http://www-hello.iteye.com/blog/646944
本文档所用文件:
iBATIS : ibatis-2.3.4.726.zip
Spring : spring-framework-2.5.6.SEC01-with-dependencies.zip
DBCP : spring-framework-2.5.6.SEC01-with-dependencies.zip
MySQL驱动:mysql-connector-java-5.1.12.zip
Spring2.5与Ibatis2.3的集成
1. 新建Web工程(如SSI)。(与Struts的集成请参考:http://www-hello.iteye.com/blog/643937)
2. 添加所需Jar包到WEB-INF/lib目录下:
2.1 iBatis包:ibatis-2.3.4.726.jar
2.2 DBCP包:commons-pool.jar,commons-dbcp.jar
2.3 Spring包:spring.jar,commons-logging.jar,log4j-1.2.15.jar,antlr-2.7.6.jar,aspectjrt.jar,aspectjweaver.jar,commons-collections.jar
2.4 MySQL驱动包:mysql-connector-java-5.1.12-bin.jar
3. 配置文件
3.1 日志配置文件(log4j.properties)
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n
log4j.logger.java.sql.PreparedStatement=DEBUT
3.2 Jdbc连接属性文件(jdbc.properties)
driverClassName=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
initialSize=1
maxActive=100
maxIdle=8
minIdle=1
3.3 Spring配置文件(applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 启用注解 -->
<context:annotation-config />
<context:component-scan base-package="cn.*" />
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!--连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!--连接池的最大值 -->
<property name="maxActive" value="${maxActive}" />
<!--最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}" />
<!--最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<!--spring整合ibatis -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>
<!--事务 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
3.4 总配置文件(SqlMapConfig.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!--映射文件-->
<sqlMap resource="cn/ssi/config/book.xml"/>
</sqlMapConfig>
3.5 实体映射文件(cn/ssi/config/book.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap>
<typeAlias alias="Book" type="cn.ssi.entity.Book" />
<!-- 添加图书 -->
<insert id="saveBook">
<selectKey keyProperty="id" resultClass="int">
SELECT
LAST_INSERT_ID() AS VALUE
</selectKey>
INSERT INTO
book(title,author,total,price,isbn,publisher)
VALUES
(#title#,#author#,#total#,#price#,#isbn#,#publisher#)
</insert>
<!-- 删除图书 -->
<delete id="deleteBook" parameterClass="int">
DELETE FROM book WHERE
id=#id#
</delete>
<!-- 通过出版社查找此出版社出版的所有图书 -->
<select id="findBooksByPublisher" parameterClass="String"
resultClass="Book">
SELECT
id,title,author,total,price,isbn,publisher
FROM
book
WHERE
publisher = #publisher#
</select>
<!-- 通过isbn查找图书 -->
<select id="findBookByISBN" parameterClass="String" resultClass="Book">
SELECT
id,title,author,total,price,isbn,publisher
FROM
book
WHERE
isbn =
#isbn#
</select>
<!-- 通过ID查找图书 -->
<select id="findBookById" parameterClass="int" resultClass="Book">
SELECT
id,title,author,total,price,isbn,publisher
FROM
book
WHERE
id = #id#
</select>
<select id="findBooks" parameterClass="Book" resultClass="Book">
SELECT
id,title,author,total,price,isbn,publisher
FROM
book
<dynamic prepend="WHERE">
<isNotEmpty prepend="AND" property="title">
(title like #title#)
</isNotEmpty>
<isNotEmpty prepend="AND" property="autor">
(author like #author#)
</isNotEmpty>
</dynamic>
</select>
<!-- 更新图书 -->
<update id="updateBook" parameterClass="Book">
UPDATE
book
SET
title=#title#,author=#author#,total=#total#,price=#price#,isbn=#isbn#,publisher=#publisher#
WHERE
id=#id#
</update>
</sqlMap>
4. 编写Java代码
4.1 Entity类(Book.java)
package cn.ssi.entity;
public class Book {
private int id;
private String title;
private String author;
private int total;
private float price;
private String isbn;
private String publisher;
public Book() {
}
public Book(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID:").append(id).append(" ");
sb.append("title:").append(title).append(" ");
sb.append("author:").append(author).append(" ");
sb.append("total:").append(total).append(" ");
sb.append("price:").append(price).append(" ");
sb.append("isbn:").append(isbn).append(" ");
sb.append("publisher:").append(publisher).append(" ");
return sb.toString();
}
}
4.2 业务类接口(BookService.java)
package cn.ssi.service;
import java.util.List;
import cn.ssi.entity.Book;
public interface BookService {
/**
* 增加图书
*
* @param book
* 图书
*/
public void save(Book book);
/**
* 删除指定图书
*
* @param id
* 图书ID号
*/
public void deleteBook(int id);
/**
* 通过出版社查找此出版社出版的所有书籍
*
* @param publisher
* 出版社
* @return 所有书籍
*/
public List<Book> findBookByPublisher(String publisher);
/**
* 根据Id查找图书
*
* @param id
* @return
*/
public Book findBookById(int id);
/**
* 更新图书
* @param book 图书
*/
public void updateBook(Book book);
}
4.3 业务类实现类(BookServiceBeanjava)
package cn.ssi.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.ssi.entity.Book;
import cn.ssi.service.BookService;
@Service
@Transactional
public class BookServiceBean implements BookService {
private @Resource(name = "sqlMapClientTemplate")
SqlMapClientTemplate sqlMapClientTemplate;
@Override
public void deleteBook(int id) {
sqlMapClientTemplate.delete("deleteBook", id);
}
@Override
public Book findBookById(int id) {
return (Book) sqlMapClientTemplate.queryForObject("findBookById", id);
}
@SuppressWarnings("unchecked")
@Override
public List<Book> findBookByPublisher(String publisher) {
return (List<Book>) sqlMapClientTemplate.queryForList(
"findBooksByPublisher", publisher);
}
@Override
public void save(Book book) {
sqlMapClientTemplate.insert("saveBook", book);
}
@Override
public void updateBook(Book book) {
sqlMapClientTemplate.update("updateBook", book);
}
}
5. 测试集成
5.1 Junit测试类(BookServiceTest.java)
package cn.ssi.book.test;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.ssi.entity.Book;
import cn.ssi.service.BookService;
public class BookServiceTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testBookService() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
BookService bookService = (BookService) ctx.getBean("bookServiceBean");
Book book = new Book();
book.setTitle("bookTest");
book.setAuthor("author");
book.setIsbn("ISBN:123456");
book.setPublisher("publisher1");
book.setPrice(45.0f);
book.setTotal(100);
bookService.save(book);
List<Book> books = bookService.findBookByPublisher("publisher1");
System.out.println("---------------BOOKS-------------------");
System.out.println("图书:" + books.size());
for (Book b : books) {
System.out.println(b);
}
}
}
5.2 运行Junit测试
---------------BOOKS-------------------
图书:1
ID:10 title:bookTest author:author total:100 price:45.0 isbn:ISBN:123456 publisher:publisher1
5.3 MySQL数据库
mysql> select * from book;
+----+----------+--------+-------+-------+-------------+------------+
| id | title | author | total | price | isbn | publisher |
+----+----------+--------+-------+-------+-------------+------------+
| 10 | bookTest | author | 100 | 45 | ISBN:123456 | publisher1 |
+----+----------+--------+-------+-------+-------------+------------+
1 row in set (0.00 sec)
集成成功。
附:
数据库角本:
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(50) default NULL,
`author` varchar(20) default NULL,
`total` int(11) default NULL,
`price` float default NULL,
`isbn` varchar(20) default NULL,
`publisher` varchar(50) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Spring2.5(全注解)+Ibatis2.3的集成
最新推荐文章于 2024-04-27 21:54:56 发布