Spring与Mybatis使用JavaConfig整合

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.0modelVersion>

    <groupId>com.springdemogroupId>
    <artifactId>spring01artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>spring01name>
    <url>http://maven.apache.orgurl>

    <properties>
        <spring.version>4.3.8.RELEASEspring.version>
        <spring.security.version>4.2.3.RELEASEspring.security.version>
        <junit.version>4.12junit.version>
        <jdk.version>1.8jdk.version>
        <jsp.version>2.2jsp.version>
        <servlet.version>3.1.0servlet.version>
        <jstl.version>1.2jstl.version>
        <slf4j-version>1.7.25slf4j-version>

        <hamcrest.core.version>1.3hamcrest.core.version>
        <mockito.core.version>2.8.9mockito.core.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.hamcrestgroupId>
            <artifactId>hamcrest-coreartifactId>
            <version>${hamcrest.core.version}version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.mockitogroupId>
            <artifactId>mockito-coreartifactId>
            <version>${mockito.core.version}version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-instrumentartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-instrument-tomcatartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-webartifactId>
            <version>${spring.security.version}version>
        dependency>
        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-configartifactId>
            <version>${spring.security.version}version>
        dependency>

        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>${jstl.version}version>
        dependency>

        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>${servlet.version}version>
            <scope>providedscope>
        dependency>

        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>${jsp.version}version>
            <scope>providedscope>
        dependency>

        <dependency>
            <groupId>javaxgroupId>
            <artifactId>javaee-web-apiartifactId>
            <version>7.0version>
            <scope>providedscope>
        dependency>

        <dependency>
            <groupId>commons-langgroupId>
            <artifactId>commons-langartifactId>
            <version>2.6version>
        dependency>

        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.20version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-dbcp2artifactId>
            <version>2.1.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>6.0.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.2.1version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>${slf4j-version}version>
        dependency>
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.5version>
        dependency>

    dependencies>
    <build>
        <finalName>spring01finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.6.1version>
                <configuration>
                    <source>${jdk.version}source>
                    <target>${jdk.version}target>
                configuration>
            plugin>
        plugins>
    build>
project>

AppConfig.java

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.springdemo.bean.UserMapper;

@EnableTransactionManagement
public class AppConfig1 {

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true");
        ds.setUsername("root");
        ds.setPassword("123456@#");
        ds.setInitialSize(5);
        return ds;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/springdemo/bean/UserMapper.xml"));
        sessionFactory.setTypeAliasesPackage("com.springdemo.bean");
        return sessionFactory.getObject();
    }

    @Bean
    public UserMapper userMapper(SqlSessionTemplate sqlSessionTemplate) throws Exception {
      return sqlSessionTemplate.getMapper(UserMapper.class);
    }

}

@EnableTransactionManagement注解是为了增加事务的支持
UserMapper.java

import java.util.List;

public interface UserMapper {
    public void insert(User user);
    public User selectUser(String userName);
    public List selectAll();
}

UserMapper.xml



<mapper namespace="com.springdemo.bean.UserMapper">
    <resultMap type="user" id="userList">
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="enabled" property="enabled" />
    resultMap>
    <insert id="insert" parameterType="user">
        insert into users(username,
        password,enabled) values(#{username}, #{password},#{enabled})
    insert>
    <select id="selectUser" parameterType="String" resultType="user">
        SELECT * FROM users WHERE username = #{username}
    select>
    <select id="selectAll" resultMap="userList" resultType="user">
        SELECT * FROM users
    select>
mapper>

User.java

public class User {
    private String username;
    private String password;
    private boolean enabled;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public boolean isEnabled() {
        return enabled;
    }
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + ", enabled=" + enabled + "]";
    }

}

App.java

public class App {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);       
        UserMapper userMapper = (UserMapper) context.getBean(UserMapper.class);
        System.out.println(userMapper.selectAll());
    }
}

ps
1、可以使用注解@MapperScan代替

    @Bean
    public UserMapper userMapper(SqlSessionTemplate sqlSessionTemplate) throws Exception {
      return sqlSessionTemplate.getMapper(UserMapper.class);
    }

自动扫描,就不用一个个接口来添加了。
2、@MapperScan(“com.springdemo.bean”)注解和

    @Bean  
    public MapperScannerConfigurer mapperScannerConfigurer(){  
        MapperScannerConfigurer mScannerConfigurer = new MapperScannerConfigurer();  
        mScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");  
        mScannerConfigurer.setBasePackage("com.springdemo.bean");
        return mScannerConfigurer;
    }

可以相互替换。
3、例子是使用接口+xml来实现的,如果是直接使用接口,就不用使用sessionFactory.setMapperLocations方法来设置xml位置了。

你可能感兴趣的:(mybatis,Spring)