public class Order implements Serializable { private static final long serialVersionUID = -7307764485708148107L; private Integer orderId; private String orderAddress; ... public class Account implements Serializable { private static final long serialVersionUID = 3337778507086494766L; private Integer accountId; private String username; //建立了一个包含关联关系 private List<Order> orders = new LinkedList<Order>(); ...
CREATE TABLE `orders` ( `order_id` int(11) NOT NULL AUTO_INCREMENT, `order_address` varchar(20) DEFAULT NULL, `account_id` int(11) DEFAULT NULL, PRIMARY KEY (`order_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; CREATE TABLE `account` ( `account_id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, PRIMARY KEY (`account_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO `account` (`account_id`, `username`) VALUES (1, 'hello'), (2, 'world'); INSERT INTO `orders` (`order_id`, `order_address`, `account_id`) VALUES (1, 'hello1', 1), (2, 'hello2', 1);
<sqlMap namespace="Account"> <typeAlias alias="account" type="com.partner4java.demo1.bean.Account" /> <typeAlias alias="order" type="com.partner4java.demo1.bean.Order" /> <!-- 简单关联方案 --> <resultMap class="account" id="accountMap"> <result property="accountId" column="account_id" /> <result property="username" column="username" /> <!-- 通过select来获取的值放入orders;select需要一个关联参数,为本处column --> <result property="orders" column="account_id" select="getOrderList" /> </resultMap> <resultMap class="order" id="orderMap"> <result property="orderId" column="order_id" /> <result property="orderAddress" column="order_address" /> </resultMap> <select id="getAccount" resultMap="accountMap"> select * from account </select> <select id="getOrderList" resultMap="orderMap"> select * from orders where account_id = #value# </select> </sqlMap>
public static void main(String[] args) throws Exception { Reader reader = Resources.getResourceAsReader("sql-map-config.xml"); SqlMapClient sqlMapClient = SqlMapClientBuilder .buildSqlMapClient(reader); List<Account> accounts = sqlMapClient.queryForList("getAccount", null); for(Account account:accounts){ System.out.println(account); } } 打印: Account [accountId=1, username=hello, orders=[Order [orderId=1, orderAddress=hello1], Order [orderId=2, orderAddress=hello2]]] Account [accountId=2, username=world, orders=[]]
<!-- N + 1查询方案,注意每个resultMap都添加了一个groupBy --> <resultMap class="order" id="orderJMap" groupBy="orders.order_id"> <result property="orderId" column="order_id" /> <result property="orderAddress" column="order_address" /> </resultMap> <resultMap class="account" id="accountJMap" groupBy="account.account_id"> <result property="accountId" column="account_id" /> <result property="username" column="username" /> <!-- 这里的resultMap为我们上面对order的定义 --> <result property="orders" resultMap="Account.orderJMap" /> </resultMap> <select id="getAccountJ" resultMap="accountJMap"> select account.account_id,account.username,orders.order_id,orders.order_address from account join orders on account.account_id = orders.account_id order by account.account_id,orders.order_id </select>
public static void main(String[] args) throws Exception { Reader reader = Resources.getResourceAsReader("sql-map-config.xml"); SqlMapClient sqlMapClient = SqlMapClientBuilder .buildSqlMapClient(reader); List<Account> accounts = sqlMapClient.queryForList("getAccountJ", null); for(Account account:accounts){ System.out.println(account); } }
<transactionManager type="JDBC"> <!-- SIMPLE是一个iBATIS内置事务管理器的名字 --> <dataSource type="SIMPLE"> ...
public static void main(String[] args) throws Exception { Reader reader = Resources.getResourceAsReader("sql-map-config.xml"); SqlMapClient sqlMapClient = SqlMapClientBuilder .buildSqlMapClient(reader); //学过jdbc的,是不是很容易理解啊? sqlMapClient.startTransaction(); long being = System.currentTimeMillis(); try { sqlMapClient.startBatch(); for(int i=0;i<1000;i++){ Account account = new Account("en5" + i, "o5", "EMPLOYEE"); sqlMapClient.insert("insertAccount", account); } sqlMapClient.executeBatch(); sqlMapClient.commitTransaction(); } catch (Exception e) { e.printStackTrace(); }finally{ sqlMapClient.endTransaction(); } System.out.println("time:" + (System.currentTimeMillis() - being)); }
public static void main(String[] args) throws Exception { Reader reader = Resources.getResourceAsReader("sql-map-config.xml"); SqlMapClient sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); Connection conn = null; SqlMapSession session = null; try { conn = sqlMapClient.getDataSource().getConnection(); conn.setAutoCommit(false); session = sqlMapClient.openSession(conn); session.insert("insertAccount", new Account("hello", "123", "EMPLOYEE")); conn.commit(); } catch (Exception e) { if(conn != null) conn.rollback(); e.printStackTrace(); }finally{ if(session != null){ session.close(); } if(conn != null){ conn.close(); } } }
<select id="queryAccount" resultClass="account" parameterClass="string"> select * from user_account <!-- 就多了一个这种标签,看这标签的起名是不是很像我们Junit里的断言啊? --> <isNotNull> where groupname = #value# </isNotNull> </select>
public static void main(String[] args) throws Exception { Reader reader = Resources.getResourceAsReader("sql-map-config.xml"); SqlMapClient sqlMapClient = SqlMapClientBuilder .buildSqlMapClient(reader); List<Account> accounts = sqlMapClient .queryForList("queryAccount", "EMPLOYEE"); for (Account account : accounts) { System.out.println(account); } }
<select id="queryAccount" resultClass="account" parameterClass="string"> select * from user_account <dynamic> <isNotNull> where groupname = #value# </isNotNull> </dynamic> </select>
只有当你想要向据诶过内容体使用open、close或prepend值时,才必须使用<dynamic>标签。
<!-- type="MEMORY",指定其高速缓存类型为MEMORY,把查询结果直接存储在内存中。 --> <cacheModel type="MEMORY" id="categoryCache"> <!-- flushOnExecute标签用于指定当某个特定高速缓存被访问时,其存储结果将被清除。 --> <flushOnExecute statement="insert" /> <flushOnExecute statement="update" /> <flushOnExecute statement="delete" /> <!-- 每一种类型的高速缓存模型都有一些专用于它自己配置的特性,property标签就是用于完成这些专用特性的设置的。那么属性指定该高速缓存模型将要设置的特性的名称,value指定该预定义特性的值。 --> <property name="reference-type" value="WEAK" /> </cacheModel> <select id="queryAccount" resultClass="account" parameterClass="string" cacheModel="categoryCache"> select * from user_account <dynamic> <isNotEmpty> where groupname = #value# </isNotEmpty> </dynamic> </select>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.partner4java.spring</groupId> <artifactId>5spring</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.1.1.RELEASE</spring.version> <ibatis.version>2.1.7.597</ibatis.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-sqlmap</artifactId> <version>2.3.4.726</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-core</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.9</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> </project>
driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/ibatis_test?useUnicode=true&characterEncoding=UTF-8 user=root password=123456 #初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 initialPoolSize=1 #连接池中保留的最小连接数 minPoolSize=1 #连接池中保留的最大连接数。Default: 15 maxPoolSize=300 #最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 maxIdleTime=60 #当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 acquireIncrement=5 #每60秒检查所有连接池中的空闲连接。Default: 0 idleConnectionTestPeriod=120 #定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 #acquireRetryAttempts=30 #两次连接中间隔时间,单位毫秒。Default: 1000 #acquireRetryDelay=1000 #连接关闭时默认将所有未提交的操作回滚。Default: false #autoCommitOnClose=false #JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements # 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 # 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 #maxStatements=100 #maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 #maxStatementsPerConnection= #c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能 # 通过多线程实现多个操作同时被执行。Default: 3 #numHelperThreads=3 #当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0 # 的数据源时。Default: null #overrideDefaultUser=root #与overrideDefaultUser参数对应使用的一个参数。Default: null #overrideDefaultPassword= #定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意: # 测试的表必须在初始数据源的时候就存在。Default: null #preferredTestQuery=select id from test where id=1 #用户修改系统配置参数执行前最多等待300秒。Default: 300 #propertyCycle=300 #因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 # 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable # 等方法来提升连接测试的性能。Default: false #testConnectionOnCheckout=false #如果设为true那么在取得连接的同时将校验连接的有效性。Default: false #testConnectionOnCheckin=true #c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么 #属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试 #使用。Default: null #automaticTestTable=Test #获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 # 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 # 获取连接失败后该数据源将申明已断开并永久关闭。Default: false #breakAfterAcquireFailure=false #当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出 # SQLException,如设为0则无限期等待。单位毫秒。Default: 0 #checkoutTimeout=5000 #通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。 # Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester #connectionTesterClassName= #指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可 # Default: null #factoryClassLocation= #maxConnectionAge=400
<?xml version="1.0" encoding="GBK"?> <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:property-placeholder location="classpath:jdbc-c3p0.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${driverClass}"/> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> <property name="initialPoolSize" value="${initialPoolSize}"/> <property name="minPoolSize" value="${minPoolSize}"/> <property name="maxPoolSize" value="${maxPoolSize}"/> <property name="maxIdleTime" value="${maxIdleTime}"/> <property name="acquireIncrement" value="${acquireIncrement}"/> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"/> </bean> </beans>
public class Account implements Serializable { private static final long serialVersionUID = -6876471972027832806L; private int userid; private String username; private String password; private String groupname; ...
<?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 namespace="Account"> <typeAlias alias="account" type="com.partner4java.demo.entity.Account" /> <select id="queryAccount" resultClass="account" parameterClass="string"> select * from user_account <dynamic> <isNotEmpty> where groupname = #value# </isNotEmpty> </dynamic> order by userid desc </select> <insert id="insertAccount" parameterClass="account"> insert into user_account(username,password,groupname) values(#username#,#password#,#groupname#) </insert> </sqlMap>
<?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> <settings useStatementNamespaces="true" /> <sqlMap resource="ibatis/Account.xml" /> </sqlMapConfig>
<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <aop:aspectj-autoproxy /> <context:component-scan base-package="com.partner4java" /> <import resource="classpath:META-INF/spring/datasource-c3p0.xml" /> <!-- SqlMapClientFactoryBean是个Spring工厂Bean,用于生成SqlMapClient。 iBATIS API的核心是SqlMapClient接口。 SqlMapClient大致相当于Hibernate的Session或者JPA的EntityManager,用于执行全部的数据访问操作。 --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:ibatis/sql-map-config.xml"/> </bean> <!-- SqlMapClientTemplate包裹了一个SqlMapClient来透明的打开和关闭会话,好捕获抛出的SQLException。 --> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient" ref="sqlMapClient"/> </bean> </beans>
public interface AccountService { List<Account> query(String groupname); void add(Account account); } @Service public class AccountServiceBean implements AccountService { @Autowired private SqlMapClientTemplate sqlMapClientTemplate; public void setSqlMapClientTemplate( SqlMapClientTemplate sqlMapClientTemplate) { this.sqlMapClientTemplate = sqlMapClientTemplate; } public List<Account> query(String groupname) { return sqlMapClientTemplate.queryForList("Account.queryAccount", groupname); } public void add(Account account) { sqlMapClientTemplate.insert("Account.insertAccount", account); } }
public class AccountServiceBeanTest { ApplicationContext applicationContext; private AccountService accountService; @Before public void setUp() throws Exception { applicationContext = new ClassPathXmlApplicationContext( "META-INF/spring/beans.xml"); accountService = applicationContext.getBean("accountServiceBean", AccountService.class); } @Test public void testQuery() { System.out.println(accountService.query(null)); } }