spring ibatis example

This commit is contained in:
sxyx2008
2014-07-22 17:56:47 +08:00
parent d4d4a67f01
commit 0a8d56b642
17 changed files with 688 additions and 2976 deletions
File diff suppressed because it is too large Load Diff
+135
View File
@@ -0,0 +1,135 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>maven-framework-project</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>spring-ibatis-example</artifactId>
<name>spring-ibatis-example</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<slf4j.version>1.7.5</slf4j.version>
<logback.version>1.0.12</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.googlecode.log4jdbc</groupId>
<artifactId>log4jdbc</artifactId>
<version>1.2</version>
</dependency>
<!-- iBatis support -->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-sqlmap</artifactId>
<version>2.3.4.726</version>
</dependency>
<!-- Database connectivity support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Proxy support (Mandatory) -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Internal dependency (Required) -->
<dependency>
<groupId>asm</groupId>
<artifactId>asm-util</artifactId>
<version>3.3.1</version>
</dependency>
<!-- Internal dependency (Required) -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
<version>2.4</version>
<scope>compile</scope>
<!-- This excludes the transitive dependency on JMS -->
<exclusions>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.170</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,18 @@
package org.spring.ibatis.example.dao;
import java.util.List;
import org.spring.ibatis.example.model.Product;
public interface ProductDao {
List<Product> listAll();
List<Product> selectLikeName(String name);
boolean save(Product product);
boolean update(Product product);
Product getModel(int id);
}
@@ -0,0 +1,85 @@
package org.spring.ibatis.example.dao.impl;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.spring.ibatis.example.dao.ProductDao;
import org.spring.ibatis.example.model.Product;
import org.springframework.stereotype.Repository;
import com.ibatis.sqlmap.client.SqlMapClient;
@Repository(value="productDaoImpl")
public class ProductDaoImpl implements ProductDao {
private SqlMapClient sqlMapClient;
public SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
//将sqlMapClient注入
@Resource(name="sqlMapClient")
public void setSqlMapClient(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
@SuppressWarnings("unchecked")
public List<Product> listAll() {
try {
return getSqlMapClient().queryForList("org.spring.ibatis.example.model.Product.selectAll");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean save(Product product) {
try {
Object object = getSqlMapClient().insert("org.spring.ibatis.example.model.Product.save", product);
return object==null?false:true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public boolean update(Product product) {
try {
int n=getSqlMapClient().update("org.spring.ibatis.example.model.Product.update", product);
return n==1?true:false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public Product getModel(int id) {
try {
return (Product) getSqlMapClient().queryForObject("org.spring.ibatis.example.model.Product.selectById", id);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public List<Product> selectLikeName(String name) {
try {
return getSqlMapClient().queryForList("org.spring.ibatis.example.model.Product.selectProductLikeName",name);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
@@ -0,0 +1,23 @@
package org.spring.ibatis.example.model;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Category implements Serializable {
private int id;
private String name;
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;
}
}
@@ -0,0 +1,55 @@
package org.spring.ibatis.example.model;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Product implements Serializable {
private int id;
private String name;
private float price;
private String description;
private String categoryid;
private Category category;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategoryid() {
return categoryid;
}
public void setCategoryid(String categoryid) {
this.categoryid = categoryid;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
@@ -0,0 +1,18 @@
package org.spring.ibatis.example.service;
import java.util.List;
import org.spring.ibatis.example.model.Product;
public interface ProductService {
List<Product> listAll();
boolean save(Product product);
boolean update(Product product);
Product getModel(int id);
List<Product> selectLikeName(String name);
}
@@ -0,0 +1,45 @@
package org.spring.ibatis.example.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.spring.ibatis.example.dao.ProductDao;
import org.spring.ibatis.example.model.Product;
import org.spring.ibatis.example.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service(value="productServiceImpl")
public class ProductServiceImpl implements ProductService {
@Resource(name="productDaoImpl")
private ProductDao productDao;
@Transactional(propagation=Propagation.REQUIRED)
public List<Product> listAll() {
return productDao.listAll();
}
@Transactional(propagation=Propagation.REQUIRED)
public boolean save(Product product) {
return productDao.save(product);
}
@Transactional(propagation=Propagation.REQUIRED)
public boolean update(Product product) {
return productDao.update(product);
}
@Transactional(propagation=Propagation.REQUIRED)
public Product getModel(int id) {
return productDao.getModel(id);
}
@Override
public List<Product> selectLikeName(String name) {
return productDao.selectLikeName(name);
}
}
@@ -0,0 +1,25 @@
DROP TABLE IF EXISTS product;
DROP TABLE IF EXISTS category;
CREATE TABLE category (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) DEFAULT NULL,
PRIMARY KEY (id)
);
insert into category(id,name) values (1,'手机'),(2,'平板电脑'),(3,'笔记本');
CREATE TABLE product (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) DEFAULT NULL,
price float DEFAULT NULL,
description varchar(200) DEFAULT NULL,
categoryid int(11) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT fk_product_category FOREIGN KEY (categoryid) REFERENCES category (id)
);
insert into product(id,name,price,description,categoryid) values (1,'ipad2',3000,'ipad2',2),(2,'ipad3',4000,'ipad3',2),(3,'ipad4',3000,'ipad4',2),(4,'SONY手机',79,'SONY手机,手机中的战斗机!',1),(5,'Surface平板电脑',4680,'Surface平板电脑',2);
@@ -0,0 +1,4 @@
driverClassName=net.sf.log4jdbc.DriverSpy
username=sa
password=
url=jdbc:log4jdbc:h2:./target/ibatis
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<jmxConfigurator />
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>target/maven-framework-project.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>target/maven-framework-project.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- project default level -->
<logger name="org.spring.ibatis.example" level="INFO" />
<logger name="org.springframework.data" level="INFO" />
<logger name="org.springframework.core" level="INFO" />
<logger name="org.springframework.beans" level="INFO" />
<logger name="org.springframework.context" level="INFO" />
<logger name="org.springframework.orm" level="INFO" />
<!-- <logger name="jdbc.sqltiming" level="INFO"/> -->
<logger name="jdbc.sqlonly" level="INFO" />
<!--
<logger name="org.apache.shiro" level="TRACE" />
<logger name="org.apache.shiro.util.ThreadContext" level="WARN" />
<logger name="org.apache.shiro.cache.ehcache.EhCache" level="WARN" />
-->
<root level="WARN">
<appender-ref ref="console" />
<appender-ref ref="rollingFile" />
</root>
</configuration>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="org.spring.ibatis.example.model.Category">
<typeAlias alias="category" type="org.spring.ibatis.example.model.Category"/>
<select id="selectById" resultClass="category" parameterClass="int">
select * from category where id=#id#
</select>
</sqlMap>
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="org.spring.ibatis.example.model.Product">
<typeAlias alias="product" type="org.spring.ibatis.example.model.Product"/>
<resultMap class="product" id="ProductMap">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="price" column="price"/>
<result property="description" column="description"/>
<result property="categoryid" column="categoryid"/>
<!-- 关联查询 查询org.spring.ibatis.example.model.Category.selectById 将categoryid传递进去-->
<result property="category" column="categoryid" select="org.spring.ibatis.example.model.Category.selectById"/>
</resultMap>
<cacheModel id="cache-product" type="OSCACHE" readOnly="true">
<flushInterval hours="24"></flushInterval>
<property name="cache-size" value="50"></property>
</cacheModel>
<select id="selectAll" resultMap="ProductMap" cacheModel="cache-product">
select * from product
</select>
<select id="selectProductLikeName" resultMap="ProductMap" parameterClass="java.lang.String" cacheModel="cache-product">
select * from product where name like concat('%',#name#,'%')
</select>
<select id="selectById" resultMap="ProductMap" parameterClass="int" cacheModel="cache-product">
select * from product where id=#id#
</select>
<insert id="save" parameterClass="product">
insert into product (name,price,description,categoryid) values (#name#,#price#,#description#,#categoryid#)
</insert>
<update id="update" parameterClass="product">
<![CDATA[
update product set name=#name#,price=#price#,description=#description# where id=#id#
]]>
</update>
</sqlMap>
@@ -0,0 +1,11 @@
#不缓存到内存
cache.memory=false
#缓存持久化实现类,磁盘持久化监听器
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener
#缓存磁盘路径,以后注意观察该目录生成的内容
cache.path=e:\\OSCache\\cache
#选择一种缓存算法,还可选 FIFOCache、UnlimitedCache
cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache
@@ -0,0 +1,49 @@
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<context:component-scan base-package="org.spring.ibatis.example"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<jdbc:initialize-database data-source="dataSource" enabled="false">
<jdbc:script location="classpath:init.sql" encoding="UTF-8"/>
</jdbc:initialize-database>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<property name="url" value="${url}"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
errorTracingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="true"
/>
<!--
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.p6spy.engine.spy.P6SpyDriver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/sample"/>
<property name="JDBC.Username" value="user"/>
<property name="JDBC.Password" value="mypass"/>
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumCheckoutTime" value="120000"/>
<property name="Pool.TimeToWait" value="500"/>
<property name="Pool.PingQuery" value="select 1 from ACCOUNT"/>
<property name="Pool.PingEnabled" value="false"/>
<property name="Pool.PingConnectionsOlderThan" value="1"/>
<property name="Pool.PingConnectionsNotUsedFor" value="1"/>
</dataSource>
</transactionManager>
-->
<sqlMap resource="org/spring/ibatis/example/model/Category.xml"/>
<sqlMap resource="org/spring/ibatis/example/model/Product.xml"/>
</sqlMapConfig>
@@ -0,0 +1,73 @@
package org.spring.ibatis.example.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.spring.ibatis.example.model.Product;
import org.spring.ibatis.example.service.ProductService;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations={"classpath:spring-ibatis.xml"})
@RunWith(value=SpringJUnit4ClassRunner.class)
public class ProductServiceImplTest {
@Resource(name="productServiceImpl")
private ProductService productService;
@Test
public void listAll(){
List<Product> lists=productService.listAll();
for (Product product : lists) {
System.out.println(product.getName()+"\t"+product.getDescription()+"\t"+product.getCategory().getId()+"\t"+product.getCategory().getName());
}
}
@Test
public void save(){
Product product=new Product();
product.setName("ipad2");
product.setPrice(3000.f);
product.setDescription("ipad2");
product.setCategoryid("1");
boolean b=productService.save(product);
System.out.println(b);
}
@Test
public void update(){
Product product=productService.getModel(3);
product.setName("戴尔");
product.setDescription("戴尔笔记本");
boolean b=productService.update(product);
System.out.println(b);
}
@Test
public void getModel(){
Product product1=productService.getModel(2);
System.out.println(product1.getName()+","+product1.getCategory().getName());
Product product2=productService.getModel(2);
System.out.println(product2.getName()+","+product2.getCategory().getName());
Product product3=productService.getModel(2);
System.out.println(product3.getName()+","+product3.getCategory().getName());
Product product4=productService.getModel(2);
System.out.println(product4.getName()+","+product4.getCategory().getName());
}
@Test
public void selectLikeName(){
List<Product> lists=productService.selectLikeName("pad");
for (Product product : lists) {
System.out.println(product.getName()+"\t"+product.getDescription()+"\t"+product.getCategory().getId()+"\t"+product.getCategory().getName());
}
}
}