SSM框架之--spring(二)spring集成mybatis

(一)spring集成mybatis第一种方式

1.添加jar包 (18个)

【mybatis】 4个
mybatis-3.1.1.jar
log4j-1.2.16.jar
asm-3.3.1.jar
cglib-2.2.2.jar
【mybatis-spring】 1个
mybatis-spring-1.2.1.jar
【spring】 10个
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
commons-logging-1.1.1.jar

    spring-web-3.2.4.RELEASE.jar

    spring-aop-3.2.4.RELEASE.jar
    spring-jdbc-3.2.4.RELEASE.jar
    spring-tx-3.2.4.RELEASE.jar
    spring-test-3.2.4.RELEASE.jar

【MYSQL驱动包】 1个
mysql-connector-java-5.0.4-bin.jar
【数据库连接池】 2个
commons-dbcp-1.4.jar
commons-pool-1.6.jar
共18个jar包

2.数据库表

CREATE TABLE user(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT);
)

3.实体类:User

public class User implements Serializable{
private int id;
private String name;
private int age;
//set,get方法
}

4.DAO接口:UseDaor

package com.dao.inter;

import java.util.List;
import com.po.User;

public interface UserDao {
//一.增加
public int addUser(User user);
//二.删除
public int deleteUser(User user);
//三.修改
public int updateUser(User user);
//四.查1
public User getUserById(Integer userid);
//五.按SQL语句查
public List getPageByQuery(String sql);
//六.查询总共有多少条记录
public int getTotalRecordSum(String sql);

}

5.DAO接口:UserDaoImpl.java

package com.dao.impl;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.dao.inter.UserDao;
import com.po.User;

public class UserDaoImpl implements UserDao {

private SqlSession sqlSession;

public void setSqlSession(SqlSession sqlSession) {
    this.sqlSession = sqlSession;
}

@Override
public int addUser(User user) {

    int count;
    String statement = "com.po.userMapper.addUser";

    count = sqlSession.insert(statement, user);

    return count;
}

@Override
public int deleteUser(User user) {
    int count;
    String statement = "com.po.userMapper.deleteUser";

    count = sqlSession.delete(statement, user);

    return count;
}

@Override
public int updateUser(User user) {
    int count;
    String statement = "com.po.userMapper.updateUser";

    count = sqlSession.update(statement, user);

    return count;
}

@Override
public User getUserById(Integer userid) {
    User user = null;

    String statement = "com.po.userMapper.getUser";

    user = sqlSession.selectOne(statement, userid);

    return user;
}

@Override
public List getPageByQuery(String sql) {
    List list = null;

    String statement = "com.po.userMapper.getPageByQuery";

    list = sqlSession.selectList(statement, sql);

    return list;
}

@Override
public int getTotalRecordSum(String sql) {
    int count = 0;
    String statement = "com.po.userMapper.getTotalRecordSum";

    count = sqlSession.selectOne(statement, sql);

    return count;
}

}

6.数据库属性文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=root
maxActive=20
maxIdle=10
maxWait=-1

7.mybatis的配置文件conf.xml



<configuration>

     <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
         
        <setting name="lazyLoadingEnabled" value="true"/>
           
        <setting name="aggressiveLazyLoading" value="false"/>
    settings>

    <typeAliases>
        <package name="com.po"/>
    typeAliases>

    <mappers>
        <mapper resource="com/po/userMapper.xml"/>

    mappers>

configuration>

8.SQL映射文件:userMapper.xml




<mapper namespace="com.po.userMapper">

    <insert id="addUser" parameterType="User">
        insert into user values(null,#{name}, #{age});
    insert>

    <delete id="deleteUser" parameterType="User">
        delete from user where id=#{id}
    delete>

    <update id="updateUser" parameterType="User">
        update user set name=#{name},age=#{age} where id=#{id}
    update>

    <select id="getUserById" parameterType="java.lang.Integer" resultType="User">
        select * from user where id=#{id}
    select>

    <select id="getPageByQuery" statementType="STATEMENT" parameterType="java.lang.String" resultType="User">
        ${value}
    select>

    <select id="getTotalRecordSum" statementType="STATEMENT" parameterType="java.lang.String" resultType="int">
        ${value}
    select>
mapper>

9.spring的配置文件:applicationContent.xml

<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"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    ">

    <context:property-placeholder location="classpath:db.properties" />

    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />

        <property name="maxActive" value="${maxActive}" />
        <property name="maxIdle" value="${maxIdle}" />
        <property name="maxWait" value="${maxWait}" />
    bean>

    
    

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

BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭。除以上必须的数据源属性外,还有一些常用的属性:
defaultAutoCommit:设置从数据源中返回的连接是否采用自动提交机制,默认值为 true;
defaultReadOnly:设置数据源是否仅能执行只读操作, 默认值为 false;
maxActive:最大连接数据库连接数,设置为0时,表示没有限制;
maxIdle:最大等待连接中的数量,设置为0时,表示没有限制;
maxWait:最大等待秒数,单位为毫秒, 超过时间会报出错误信息;
validationQuery:用于验证连接是否成功的查询SQL语句,SQL语句必须至少要返回一行数据, 如你可以简单地设置为:“select count(*) from user”;
removeAbandoned:是否自我中断,默认是 false ;
removeAbandonedTimeout:几秒后数据连接会自动断开,在removeAbandoned为true,提供该值;
logAbandoned:是否记录中断事件, 默认为 false;

SqlSessionTemplate的构造方法

public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
}

10.测试代码:Test.java

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.dao.inter.UserDao;
import com.po.User;

public class Test {
    public static void main(String[] args) {

        ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");

        UserDao userDao = (UserDao) context.getBean("userDaoImpl");

        User user = new User();
        user.setName("赵英龙");
        user.setAge(22);

        userDao.addUser(user);
    }
}

11.在web应用程序中使用spring

在web.xml中加入

<listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  listener-class>
listener>

(二)spring集成mybatis第二种方式

使用动态代理的方式生成Dao实现类,并且mybatis的中心配置文件conf.xml交给spring管理

1.添加jar包

【mybatis】 4个
mybatis-3.1.1.jar
log4j-1.2.16.jar
asm-3.3.1.jar
cglib-2.2.2.jar
【mybatis-spring】 1个
mybatis-spring-1.2.1.jar
【spring】 10个
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
commons-logging-1.1.1.jar

    spring-web-3.2.4.RELEASE.jar

    spring-aop-3.2.4.RELEASE.jar
    spring-jdbc-3.2.4.RELEASE.jar
    spring-tx-3.2.4.RELEASE.jar
    spring-test-3.2.4.RELEASE.jar

【MYSQL驱动包】 1个
mysql-connector-java-5.0.4-bin.jar
【数据库连接池】 2个
commons-dbcp-1.4.jar
commons-pool-1.6.jar

2.数据库表

CREATE TABLE user(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT);
)

3.实体类:User

public class User implements Serializable{
private int id;
private String name;
private int age;
//set,get方法
}

4.DAO接口:UserMapper

package com.dao.inter;

import java.util.List;
import com.po.User;

public interface UserMapper {
//一.增加
public int addUser(User user);
//二.删除
public int deleteUser(User user);
//三.修改
public int updateUser(User user);
//四.查1
public User getUserById(Integer userid);
//五.按SQL语句查
public List getPageByQuery(String sql);
//六.查询总共有多少条记录
public int getTotalRecordSum(String sql);
}

5.DAO接口:UserMapper.xml(不需要编写)

Spring会使用动态代理自动生成UserDaoImpl

6.SQL映射文件:UserMapper.xml




<mapper namespace="com.dao.inter.UserMapper">

    <insert id="addUser" parameterType="User">
        insert into user values(null,#{name}, #{age});
    insert>

    <delete id="deleteUser" parameterType="User">
        delete from user where id=#{id}
    delete>

    <update id="updateUser" parameterType="User">
        update user set name=#{name},age=#{age} where id=#{id}
    update>

    <select id="getUserById" parameterType="java.lang.Integer" resultType="User">
        select * from user where id=#{id}
    select>

    <select id="getPageByQuery" statementType="STATEMENT" parameterType="java.lang.String" resultType="User">
        ${value}
    select>

    <select id="getTotalRecordSum" statementType="STATEMENT" parameterType="java.lang.String" resultType="int">
        ${value}
    select>
mapper>

7.spring的配置文件:applicationContext.xml

<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"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    ">


    <context:property-placeholder location="classpath:db.properties" />

    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />

        <property name="maxActive" value="${maxActive}" />
        <property name="maxIdle" value="${maxIdle}" />
        <property name="maxWait" value="${maxWait}" />
    bean>


    
    

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="typeAliasesPackage" value="com.po" />
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="com.dao.inter" />

    bean>

    <bean id="userServiceImpl" class="com.service.impl.UserServiceImpl">
    bean>
beans>

8.数据库属性文件:db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=root
maxActive=20
maxIdle=10
maxWait=-1

9.mybatis的配置文件:conf.xml(可以省略)

如果想配置延迟加载也是在applicationContext.xml SqlSessionFactoryBean 节点中配置

10.业务层接口UserService

package com.service.inter;

import java.util.List;
import com.po.User;

public interface UserService {
// 添加
public int addUser(User user);
// 删除
public int deleteUserById(String id);
// 修改
public int updateUser(User user);
// 查1
public User getUserById(String id);
// 查所有
public List getAllUsers();

}

11.业务层实现类UserServiceimpl

package com.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.dao.inter.UserMapper;
import com.po.User;
import com.service.inter.UserService;

public class UserServiceImpl implements UserService {
    //默认spring按类型自动注入
    @Autowired
    private UserMapper userMapperImp;

    public void setUserMapperImp(UserMapper userMapperImp) {
        this.userMapperImp = userMapperImp;
    }

    @Override
    public int addUser(User user){

        int count = userMapperImp.addUser(user);
        return count;
    }

    public int deleteUserById(String id){

        User user = new User();
        user.setId(Integer.parseInt(id));
        int count = userMapperImp.deleteUser(user);
        return count;
    }

    // 修改
    public int updateUser(User user){
        int count = userMapperImp.updateUser(user);
        return count;
    }

    // 查1
    public User getUserById(String id){

        User User = null;

        User = userMapperImp.getUserById(Integer.parseInt(id));
        return User;
    }

    @Override
    public List getAllUsers(){
        List list = null;

        String sql = "select * from User";
        list = userMapperImp.getPageByQuery(sql);
        return list;
    }



}

12.日志处理

在src下加入log4g.properties属性文件,使用debug控制台打印的信息过多,可以把日志级别调成ERROR即可
log4j.properties\uFF0C
log4j.rootLogger=ERROR, Console
#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

13.测试类

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.po.User;
import com.service.inter.UserService;

public class Test {
public static void main(String[] args) {

    ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");

    UserService userService = (UserService) context.getBean("userServiceImpl");

    User user = new User();
    user.setName("zhangsan");
    user.setAge(22);
    userService.addUser(user);
}

}

14.在web应用程序中使用spring

在web.xml中加入

  
   org.springframework.web.context.ContextLoaderListener
  

附常见错误
Failed to read candidate component class: file [D:\jidi16WorkSpace2\Mybatis_Spring_2\WebRoot\WEB-INF\classes\com\dao\inter\UserMapper.class]; nested exception is org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn’t supported yet: file [D:\jidi16WorkSpace2\Mybatis_Spring_2\WebRoot\WEB-INF\classes\com\dao\inter\UserMapper.class]; nested exception is java.lang.IllegalArgumentException
解决方案:
把编译环境改成jdk1.6即可或者使用spring4.x版本

SSM框架之--spring(二)spring集成mybatis_第1张图片

你可能感兴趣的:(SSM框架之--spring(二)spring集成mybatis)