1.首先打开eclipse,创建一个动态web项目(也可以是Java Project,笔者使用的是动态web项目)
2.导入spring的jar包,mybatis的jar包,mybatis-spring的jar包,log4j的jar包,jdbc的jar包,common-logging的jar包,junit的jar包,然后build path
**注意**common-logging的jar包是必须的否则会报找不到这个包的异常,aopalliance.jar也是必须的,因为spring的aop(面向切面)的包依赖于此包,并且spring官网并没有这个包,需要自己上网找
3.创建mybatis需要的model,mapper包,junit需要的test包等等,笔者使用的是Mysql创建的learn数据库,并对address表进行增删改查
AddressMapper.java
public interface AddressMapper {
//向address表插入新的地址
void save(AddressModel addressModel);
//根据条件更新地址
boolean update(AddressModel addressModel);
//根据id删除地址
boolean delete(Integer address_id);
//根据id查找地址
AddressModel findById(Integer address_id);
//查找所有的地址信息
List findAll();
}
AddressMapper.xml
<mapper namespace="com.wzb.mappers.AddressMapper">
<resultMap type="addressModel" id="addressResults">
<id property="address_id" column="address_id"/>
<result property="address_country" column="address_country" />
<result property="address_province" column="address_province" />
<result property="address_city" column="address_city" />
<result property="address_county" column="address_county" />
<result property="address_town" column="address_town" />
<result property="address_village" column="address_village" />
<result property="uniqueId" column="uniqueId" />
resultMap>
<insert id="save" parameterType="addressModel">
INSERT INTO `learn`.`address`
(address_country,address_province,address_city,address_county,address_town,address_village,uniqueId)
VALUES(#{address_country},#{address_province},#{address_city},#{address_county},#{address_town},#{address_village},#{uniqueId})
insert>
<update id="update" parameterType="addressModel">
UPDATE `learn`.`address`
<set>
<if test="address_country != null">
address_country = #{address_country},
if>
<if test="address_province != null">
address_province = #{address_province},
if>
<if test="address_city != null">
address_city = #{address_city},
if>
<if test="address_county != null">
address_county = #{address_county},
if>
<if test="address_town != null">
address_town = #{address_town},
if>
<if test="address_village != null">
address_village = #{address_village}
if>
set>
<where>
<if test="address_id != null">
address_id = #{address_id}
if>
<if test="uniqueId != null">
AND uniqueId = #{uniqueId}
if>
where>
update>
<delete id="delete" parameterType="int">
DELETE FROM `learn`.`address` WHERE address_id = #{address_id}
delete>
<select id="findById" parameterType="int" resultType="addressModel">
SELECT * FROM `learn`.`address` WHERE address_id = #{address_id}
select>
<select id="findAll" resultMap="addressResults">
SELECT * FROM `learn`.`address`
select>
mapper>
AddressModel.java
public class AddressModel {
//定义本类的私有属性,这些属性都是client表的列名
private Integer address_id;
private String address_country;
private String address_province;
private String address_city;
private String address_county;
private String address_town;
private String address_village;
private String uniqueId;
//构造方法
public AddressModel() {
}
public AddressModel(String address_country, String address_province, String address_city, String address_county, String address_town, String address_village, String uniqueId) {
this.address_country = address_country;
this.address_province = address_province;
this.address_city = address_city;
this.address_county = address_county;
this.address_town = address_town;
this.address_village = address_village;
this.uniqueId = uniqueId;
}
public AddressModel(Integer address_id, String address_country, String address_province, String address_city, String address_county, String address_town, String address_village, String uniqueId) {
this.address_id = address_id;
this.address_country = address_country;
this.address_province = address_province;
this.address_city = address_city;
this.address_county = address_county;
this.address_town = address_town;
this.address_village = address_village;
this.uniqueId = uniqueId;
}
//成员变量的设置和获取方法
public Integer getAddress_id() {
return address_id;
}
public void setAddress_id(Integer address_id) {
this.address_id = address_id;
}
public String getAddress_country() {
return address_country;
}
public void setAddress_country(String address_country) {
this.address_country = address_country;
}
public String getAddress_province() {
return address_province;
}
public void setAddress_province(String address_province) {
this.address_province = address_province;
}
public String getAddress_city() {
return address_city;
}
public void setAddress_city(String address_city) {
this.address_city = address_city;
}
public String getAddress_county() {
return address_county;
}
public void setAddress_county(String address_county) {
this.address_county = address_county;
}
public String getAddress_town() {
return address_town;
}
public void setAddress_town(String address_town) {
this.address_town = address_town;
}
public String getAddress_village() {
return address_village;
}
public void setAddress_village(String address_village) {
this.address_village = address_village;
}
public String getUniqueId() {
return uniqueId;
}
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
//重写toString方法
@Override
public String toString() {
return "AddressModel{" +
"address_id=" + address_id +
", address_country='" + address_country + '\'' +
", address_province='" + address_province + '\'' +
", address_city='" + address_city + '\'' +
", address_county='" + address_county + '\'' +
", address_town='" + address_town + '\'' +
", address_village='" + address_village + '\'' +
", uniqueId='" + uniqueId + '\'' +
'}';
}
}
TestAddress.java
public class TestAddress {
//封装sqlSession的实例作为成员变量
private SqlSession sqlSession = null;
//封装stationMapper实例作为成员变量
private AddressMapper addressMapper = null;
//创建一个日志对象作为成员变量
private Logger logger = Logger.getLogger(AddressMapper.class);
//执行测试方法之前的方法
@Before
public void setUp() throws Exception {
/**
* 1.在执行测试方法前实例化sqlSession
* 2.在执行测试方法前实例化clientMapper
* */
sqlSession = SqlSessionFactoryUtils.openSession();
addressMapper = sqlSession.getMapper(AddressMapper.class);
}
//执行测试方法之后的方法
@After
public void tearDown() throws Exception {
//执行完测试方法关闭数据库回话
sqlSession.close();
}
//向address表插入新的地址
@Test
public void testSave() {
logger.info("向address表插入新的地址!");
//声明一个AddressModel类的对象作为要插入的地址信息
AddressModel addressModel = new AddressModel();
//给AddressModel类的对象的属性设置属性值
addressModel.setAddress_country("中国");
addressModel.setAddress_province("河南");
addressModel.setAddress_city("长安");
addressModel.setAddress_town("暨南");
addressModel.setAddress_county("织物");
addressModel.setAddress_village("牛家村");
addressModel.setUniqueId(GetUUIDUtil.getId());
try {
addressMapper.save(addressModel);
}catch(Exception e){
e.printStackTrace();
}
finally {
// 提交数据库操作
sqlSession.commit();
}
}
//根据条件更新地址
@Test
public void testUpdate() {
logger.info("根据条件更新地址!");
//声明一个AddressModel类的对象作为要插入的地址信息
AddressModel addressModel = new AddressModel();
//给AddressModel类的对象的属性设置属性值
addressModel.setAddress_id(55);
addressModel.setAddress_country("中国");
addressModel.setAddress_province("河南");
addressModel.setAddress_city("长安");
addressModel.setAddress_town("暨南");
addressModel.setAddress_county("织物");
addressModel.setAddress_village("牛家村");
//定义一个变量保存更新是否成功
boolean flag = false;
try {
flag = addressMapper.update(addressModel);
}catch(Exception e){
e.printStackTrace();
}
finally {
// 提交数据库操作
sqlSession.commit();
}
System.out.println("更新操作是否成功:"+flag);
}
//根据id删除地址
@Test
public void testDelete() {
logger.info("根据id删除地址!");
//定义一个变量保存更新是否成功
boolean flag = false;
try {
flag = addressMapper.delete(55);
}catch(Exception e){
e.printStackTrace();
}
finally {
// 提交数据库操作
sqlSession.commit();
}
System.out.println("删除操作是否成功:"+flag);
}
//根据id查找地址
@Test
public void testFindById() {
logger.info("根据id查找地址!");
//声明一个AddressModel类的对象用于保存查询结果
AddressModel addressModel = null;
try {
addressModel = addressMapper.findById(56);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("查询操作是否成功:"+addressModel);
}
//根据id查找地址
@Test
public void testFindAll() {
logger.info("根据id查找地址!");
//声明一个AddressModel类的集合对象用于保存查询结果
List addressModels = new ArrayList();
try {
addressModels = addressMapper.findAll();
}catch(Exception e){
e.printStackTrace();
}
//定义一个变量计算一共有几条数据
int count = 0;
//循环打印地址信息
for(AddressModel addressModel : addressModels){
System.out.println("第"+(++count)+"条地址:"+addressModel);
}
}
}
GetUUIDUtil.java
/**
* 该类会获取一个唯一的通用唯一识别码
* Created by Administrator on 2017/7/28 0028.
*/
public class GetUUIDUtil {
//获得全球唯一性的id
public static String getId(){
//生成的id942cd30b-16c8-449e-8dc5-028f38495bb5中间含有横杠
String id = UUID.randomUUID().toString();
//替换掉中间的那个斜杠
id=id.replace("-", "");
return id;
}
}
SqlSessionFactoryUtil.java
**注意**ApplicationContext 和ClassPathXmlApplicationContext都是org.springframework.context下面的类,如果调用其它包中的ApplicationContext 将会出现类型转换异常的信息。此外
applicationContext.xml最好放在src直接子级,否则ClassPathXmlApplicationContext中的路径要修改啊
public class SqlSessionFactoryUtils {
//得到spring的applicationContext对象(容器对象)
private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//封装一个静态的SqlSessionFactory的实例作为成员变量
private static SqlSessionFactory sqlSessionFactory;
//创建获取SqlSessionFactory(数据库对话的单例工厂)的实例的方法
public static SqlSessionFactory getSqlSessionFactory(){
//如果sqlSessionFactory不存在
if (sqlSessionFactory == null)
{
if(applicationContext != null){
//获取sqlSessionFactory的bean
sqlSessionFactory = (SqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
}
}
return sqlSessionFactory;
}
//创建一个打开SqlSession(数据库对话)的方法
public static SqlSession openSession(){
/**
* 可以看出,创建sqlsession经过了以下几个主要步骤:
1)从配置中获取Environment;
2)从Environment中取得DataSource;
3)从Environment中取得TransactionFactory(事务处理工厂);
4)从DataSource里获取数据库连接对象Connection;
5)在取得的数据库连接上创建事务对象Transaction;
6)创建Executor对象(该对象非常重要,事实上sqlsession的所有操作都是通过它完成的);
7)创建sqlsession对象。
* */
return getSqlSessionFactory().openSession();
}
}
4.配置applicationContext.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/learn" />
<property name="username" value="root" />
<property name="password" value="wzb" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wzb.mappers">property>
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:annotation-driven transaction-manager="txManager" />
beans>
注意因为这里已经定义了数据源,所以在mybatis的配置文件中不需要配置运行环境和引入jdbc.proprties文件。并且要注意mybatis-config.xml的文件路径是否正确,如果和applicationContext.xml文件同级,则可以按照笔者的方法写
5.mybatis-config.xml
<configuration>
<typeAliases>
<package name="com.wzb.model">package>
typeAliases>
<mappers>
<package name="com.wzb.mappers" />
mappers>
configuration>
这里只需要指定别名和mapper就行了
6.运行TestAddress.java进行验证是否成功。
注意运行出现错误时先查看异常内容,大部分可以看懂,实在看不懂,上网百度,不要轻言放弃。