码迷,mamicode.com
首页 > 编程语言 > 详细

MyBatis 学习总结 05 Mybatis3.x与Spring3.x整合 OLD

时间:2017-09-20 00:48:34      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:tac   sts   不用   names   builder   utf8   manager   schema   位置   

  本文通过加载mybatis-configuration.xml 文件来产生SqlSessionFactory,然后通过SqlSessionFactory去产生sqlSession,然后在通过 sqlSession对数据库表所映射的实体类进行增删改查操作。通过spring的DI和IOC,能产生对象并管理对象的声明周期,而sprig的AOP也能管理对象的事务。主要有两点:

1、需要spring通过单例的方式管理 SqlSessionFactory,并用 SqlSessionFactory 去创建 sqlSession
2、持久层的 mapper 需要spring 管理

  本文源码脚本的下载地址是: http://ovy7j2mnc.bkt.clouddn.com/mybatisSpringPro.rar

1 准备建数据库和表脚本

DROP database IF EXISTS `myDb2`;

create database myDb2;

use myDb2;DROP TABLE IF EXISTS `User`;
CREATE TABLE `User` ( 
`id` int(11) NOT NULL AUTO_INCREMENT, 
`name` varchar(255) DEFAULT NULL, 
`age` int(11) DEFAULT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

2 创建工程

  使用Maven创建JAVA工程,名称为 mybatisSpringPro。

pom.xml的参考内容为: 

<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.bank</groupId>
  <artifactId>mybatisSpringPro</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mybatisSpringPro</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>3.2.18.RELEASE</spring.version>
    
  </properties>

  <dependencies>
   <!--mysql数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--log4j日志包 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.6.1</version>
        </dependency>
        <!-- mybatis ORM框架 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- JUnit单元测试工具 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
        <!--mybatis-spring适配器 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--Spring框架核心库 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- aspectJ AOP 织入器 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
        <!--Spring java数据库访问包,在本例中主要用于提供数据源 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

         <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->  
        <dependency>  
            <groupId>commons-dbcp</groupId>  
            <artifactId>commons-dbcp</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        
  </dependencies>
  
  
</project>

 

log4j.properties

log4j.rootLogger=DEBUG, Console 

log4j.appender.Console=org.apache.log4j.ConsoleAppender    
log4j.appender.Console.layout=org.apache.log4j.PatternLayout    
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n      
log4j.logger.java.sql.ResultSet=INFO    
log4j.logger.org.apache=INFO    
log4j.logger.java.sql.Connection=DEBUG    
log4j.logger.java.sql.Statement=DEBUG    
log4j.logger.java.sql.PreparedStatement=DEBUG

 

3 user表所对应的实体类

新建 User.java

package com.mybatis.pojo;

/**
 * 
 * user表所对应的实体类
 * 
 * */
public class User  
{
    //实体类的属性和表的字段名称一一对应
    private int id;
    
    private String username ;
    
    private int age;
    
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    @Override
    public String toString()
    {
        return "User [id=" + id + ", username=" + username + ", age=" + age + "]";
    }

 
}

 

4 持久层的开发

持久层选用MyBatis,先编写一个配置文件,然后用自动化工具生成dao层以下的所有代码,配置文件generatorConfig.xml供生成器用,详细的内容请看我前面的几篇博客

generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--数据库驱动-->
    <classPathEntry    location="mysql-connector-java-5.1.6.jar"/>
    <context id="DB2Tables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
         <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/myDb2" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
         <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.bank.model" targetProject="src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
         <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.bank.mapping" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.bank.dao" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成对应表及类名-->
        <table tableName="person" domainObjectName="Person" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

上面的路径请酌情修改,保存之后在cmd下面 进入生成器的jar包所在的文件夹,然后执行以下命令:

java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite

 

5 建立一个 mybatis.cfg.xml 文件,该文件是MyBatis的重要配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
         
    <mappers>  
       <mapper resource="com/mybatis/mapper/UserMapper.xml"/>  
    </mappers>  
    
    
</configuration>

 

6 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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/aop                
     http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
      
     <!-- 加载Spring配置文件 -->
    <context:property-placeholder location="classpath*:db.properties" />
    
    <!-- 配置数据源-->  
    <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName">  
            <value>${jdbc.driver}</value>  
        </property>  
        <property name="url">  
            <value>${jdbc.url}</value>  
        </property>  
        <property name="username">  
            <value>${jdbc.username}</value>  
        </property>  
        <property name="password">  
            <value>${jdbc.password}</value>  
        </property>  
    </bean>  

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    <property name="dataSource" ref="jdbcDataSource" />  
    <property name="configLocation" value="classpath:mybatis.cfg.xml"></property>  
</bean>  

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    <property name="mapperInterface" value="com.mybatis.mapper.UserMapper"></property>  
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
</bean>  
</beans>

注意: 在定义SqlSessionFactoryBean的时候,dataSource属性是必须指定的,它表示用于连接数据库的数据源。当然,我们也可以指定一些其他的属性,下面简单列举几个:

  • mapperLocations:它表示我们的Mapper文件存放的位置,当我们的Mapper文件跟对应的Mapper接口处于同一位置的时候可以不用指定该属性的值。
  • configLocation:用于指定Mybatis的配置文件位置。如果指定了该属性,那么会以该配置文件的内容作为配置信息构建对应的SqlSessionFactoryBuilder,但是后续属性指定的内容会覆盖该配置文件里面指定的对应内容。
  • typeAliasesPackage:它一般对应我们的实体类所在的包,这个时候会自动取对应包中不包括包名的简单类名作为包括包名的别名。多个package之间可以用逗号或者分号等来进行分隔。(value的值一定要是包的全名)

 

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myDb?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

 

 7 UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
<mapper namespace="com.mybatis.mapper.UserMapper">
     
 <select id="getUser" parameterType="com.mybatis.pojo.User" resultType="com.mybatis.pojo.User">  
        SELECT * FROM user WHERE username=#{username} AND age=#{age}  
</select>  

<insert id="addUser" parameterType="com.mybatis.pojo.User"  >  
   INSERT INTO user (id,username,age) VALUES (#{id},#{username},#{age})  
</insert>  

<update id="updateUser" parameterType="com.mybatis.pojo.User">  
    UPDATE user SET username=#{username} WHERE id=#{id}  
</update>  

<delete id="deleteUser" parameterType="int">  
    DELETE FROM user WHERE id=#{id}  
</delete>  
     
</mapper>

 

8 编写存储层代码

新建UserMapper.java

package com.mybatis.mapper;

import com.mybatis.pojo.User;

/**
 * 
 */
public interface UserMapper
{
    
     public User getUser(User user);
    
     public void addUser(User user);
     
     public void updateUser(User user);
     
     public void deleteUser(int UserId);
    
    
}

 

7 测试方法

package mybatisSpringPro;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mybatis.mapper.UserMapper;
import com.mybatis.pojo.User;

public class UserMapperTest
{
    ApplicationContext ctx = null; 
            
     @Before
     public void setUp() throws Exception {
         ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
     }
     
     @Test
     public void testAdd() throws Exception {
        try{
               UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
               System.out.println( "userMapper=" + userMapper);
               User user=new User();
               user.setUsername("zhaoliu");
               user.setAge(21);
             userMapper.addUser(user);
             
             User user2=new User();
               user2.setUsername("wangwu");
               user2.setAge(22);
               userMapper.addUser(user2);
               
             System.out.println("添加成功");
        }catch(Exception e){
            e.printStackTrace();
        }
             
     }
        
     @Test
        public void testSel()  {
           try{
               UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
              System.out.println( "userMapper=" + userMapper);
              User user=new User();
              user.setUsername("zhaoliu");
              user.setAge(21);
              User oneUser = userMapper.getUser(user);
              
            System.out.println("* oneUser=" + oneUser);
                
           }catch(Exception e){
               e.printStackTrace();
           }
                
        }
     
     @Test
        public void testUpdate(){
        //修改数据
        User user=new User();
          user.setUsername("aaa");
          user.setId( 3);
          
          try{
              UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
              userMapper.updateUser(user);
              
              System.out.println("修改成功");
          }catch(Exception e){
              e.printStackTrace();
          }
              
     }
     
     @Test
        public void testDel(){
            try{
                  UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
                  userMapper.deleteUser(9);
                  
                  System.out.println("删除成功");
              }catch(Exception e){
                  e.printStackTrace();
              }
         
     }
     
}

 

 

 

 

  

 

资料参考:

http://qiuqiu0034.iteye.com/blog/1172298

 

MyBatis 学习总结 05 Mybatis3.x与Spring3.x整合 OLD

标签:tac   sts   不用   names   builder   utf8   manager   schema   位置   

原文地址:http://www.cnblogs.com/wangshuo1/p/7554598.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!