Ibatis和Spring整合...从零开始,做一个小例子。

        本人之前没有接触过服务器方面的东西,一直都是用Android客户端,所以,现在要做这方面的东西,差不多是从零开始,我的目的很简单,直接做一个例子,从应用中去学习,我想这样的方法应该是最快掌握的了。

        首先做一个User的实体类:User.java

/**
 * @author gaoning
 * @createTime 2013-12-20
 */
public class User
{

	private int		id;
	private String	name;
	private String	password;
	private String	description;

	public String getDescription()
	{
		return description;
	}

	public void setDescription(String description)
	{
		this.description = description;
	}

	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 String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

}
然后做一个UserDao管理这些方法:

/**
 * @author gaoning
 * @createTime 2013-12-20
 */
public interface UserDao
{

	public List<User> select();

	public User selectById(int id);

	public boolean add(User user);

	public boolean delete(int id);

	public boolean update(User user);

	public List<User> selectByName(String name);

}

需要一个UserDaoInterface接口:

/**
 * @author gaoning
 * @createTime 2013-12-20
 */
public interface UserDaoInterface
{

	public void add(User user);

	public void del(int id);

	public void update(User user);

	public User selectById(int id);

	public List<User> select();

	public List<User> selectByName(String name);

}

UserDaoImpl.java实现各种增删改查的方法:

/**
 * @author gaoning
 * @createTime 2013-12-20
 */
@Component
// 主键
public class UserDaoImpl implements UserDaoInterface
{

	// 在classpath中通过通配符insert*配置transactionManager.设置事务!

	@Autowired
	@Qualifier("userImpl")
	private UserDao	userDao;

	@Override
	public void add(User user)
	{
		userDao.add(user);
	}

	@Override
	public void del(int id)
	{
		userDao.delete(id);
	}

	@Override
	public void update(User user)
	{
		userDao.update(user);
	}

	@Override
	public User selectById(int id)
	{
		return userDao.selectById(id);
	}

	@Override
	public List<User> select()
	{
		return userDao.select();
	}

	@Override
	public List<User> selectByName(String name)
	{
		// TODO Auto-generated method stub
		return userDao.selectByName(name);
	}

}

UserImpl.java文件实现UserDao接口:

/**
 * @author gaoning
 * @createTime 2013-12-20
 */
// @Component(不推荐使用)、@Repository、@Service、@Controller
// 只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了:
@Component
public class UserImpl extends SqlMapClientDaoSupport implements UserDao
{
	// 类的实现(对成员变量进行标注)
	@Autowired
	public void setSqlMapClientForAutowire(SqlMapClient sqlMapClient)
	{
		super.setSqlMapClient(sqlMapClient);
	}

	@Override
	public boolean add(User user)
	{
		getSqlMapClientTemplate().insert("insertUser", user);
		return true;
	}

	@Override
	public boolean delete(int id)
	{
		getSqlMapClientTemplate().delete("deleteUserById", id);
		System.out.println("删除学生信息的返回值:" + id + ",这里返回的是影响的行数");
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> select()
	{
		return getSqlMapClientTemplate().queryForList("selectAllUsers");
	}

	@Override
	public User selectById(int id)
	{
		User user = (User) getSqlMapClientTemplate().queryForObject(
				"selectUserById", id);
		return user;
	}

	@Override
	public boolean update(User user)
	{
		getSqlMapClientTemplate().update("updateAccount", user);
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> selectByName(String name)
	{
		// TODO Auto-generated method stub
		return getSqlMapClientTemplate().queryForList("selectUserByName", name);
	}

}

创建MySQL语句:

DROP TABLE IF EXISTS `ibatistest`.`users`;
CREATE TABLE  `ibatistest`.`users` (
  `id` varchar(50) NOT NULL default '',
  `name` varchar(50) NOT NULL default '',
  `password` varchar(50) NOT NULL default '',
  `description` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据库连接:db.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3307/ibatistest
username=root
password=123456
执行查询的文件:Users.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 namespace="User">

	<!-- Use type aliases to avoid typing the full classname every time. -->
	<typeAlias alias="User" type="cn.edu.zju.jjh.entity.User" />

	<!--
		Result maps describe the mapping between the columns returned from a
		query, and the class properties. A result map isn't necessary if the
		columns (or aliases) match to the properties exactly.
	-->
	<resultMap id="UserResult" class="User">
		<result property="id" column="id" />
		<result property="name" column="name" />
		<result property="password" column="password" />
		<result property="description" column="description" />
	</resultMap>

	<!--
		Select with no parameters using the result map for Account class.
	-->
	<select id="selectAllUsers" resultMap="UserResult">
		select * from users
	</select>

	<!--
		A simpler select example without the result map. Note the aliases to
		match the properties of the target result class.
	-->
	<select id="selectUserById" parameterClass="int" resultClass="User">
		<!--
			select id as id, name as name, password as password, description as
			description from users where id = #id#
		-->
		select * from users where id=#id#

	</select>

	<!-- Insert example, using the Account parameter class -->
	<insert id="insertUser" parameterClass="User">
		insert into users
		(id,name, password,description) values ( #id#,
		#name#, #password#,
		#description#)
	</insert>

	<!-- Update example, using the Account parameter class -->
	<update id="updateAccount" parameterClass="User">
		update users set name
		= #name#, password = #password#,
		description = #description# where id =
		#id#
	</update>

	<!-- Delete example, using an integer as the parameter class -->
	<delete id="deleteUserById" parameterClass="int">
		delete from users
		where id = #id#
	</delete>

	<!--模糊查询: 注意这里的resultClass类型,使用User类型取决于queryForList还是queryForObject -->
	<select id="selectUserByName" parameterClass="String"
		resultClass="User">
		select name,password,description from users where name
		like
		'%$name$%'
	</select>

</sqlMap>
Spring的映射文件:SqlMapConfig_spring.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>

	<!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) -->
	<sqlMap resource="Users.xml" />
	
	<!-- 
	    List more here...
	    <sqlMap resource="com/mydomain/data/Order.xml"/>
		<sqlMap resource="com/mydomain/data/Documents.xml"/>
	-->
</sqlMapConfig>

最后的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"
	xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
	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.springmodules.org/schema/ehcache  
			 http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
			 http://www.springframework.org/schema/tx 
			 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			 http://www.springframework.org/schema/aop
			 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
	default-lazy-init="true">

	<!-- 设置注解注入 -->
	<context:component-scan base-package="cn.edu.zju.jjh" />
	<!-- 设置注解事务  -->
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:db.properties</value>
			</list>
		</property>
	</bean>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName">
			<value>${driverClass}</value>
		</property>
		<property name="url">
			<value>${url}</value>
		</property>
		<property name="username">
			<value>${username}</value>
		</property>
		<property name="password">
			<value>${password}</value>
		</property>
		<property name="maxActive">
			<value>1000</value>
		</property>
		<property name="maxWait">
			<value>5000</value>
		</property>
		<property name="maxIdle">
			<value>30</value>
		</property>
		<property name="defaultAutoCommit">
			<value>true</value>
		</property>
		<!--  自动回收连接池,避免连接池泄露 -->
		<property name="removeAbandoned">
			<value>true</value>
		</property>
		<property name="removeAbandonedTimeout">
			<value>60</value>
		</property>
	</bean>

	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation" value="classpath:SqlMapConfig_spring.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref local="dataSource" />
		</property>
	</bean>

</beans> 

各位莫担心,有源码上传的:



你可能感兴趣的:(Ibatis和Spring整合...从零开始,做一个小例子。)