搭建一個Spring項目並整合MyBatis

搭建一個Spring項目

  • 步驟一:

  • 步驟二:

  • 步驟三:

  • 步驟四:

  • 步驟五:

  • 步驟六:

  • 步驟七:

  • 最終目錄結構

2. 整合MyBatis

2.1 導入pom依賴:

導入pom相關的依賴。看博客最後 附錄pom文件java

2.2 配置文件

jdbc.driver=com.mysql.jdbc.Driver
# 數據庫地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/springday01
# mysql帳號
jdbc.username=root
# mysql密碼
jdbc.password=root

2.3 建立數據庫和表

create database springday01;
use springday01;
CREATE TABLE USER(
 uid VARCHAR(32) PRIMARY KEY,
 username VARCHAR(50),
 PASSWORD VARCHAR(32)
)

2.4 編寫domain

  • 建立User類

  • 添加get 、set方法
package com.zqh.domain;

import javax.persistence.Table;
import java.io.Serializable;

/**
 * @author 漫路
 */
@Table(name = "user")
public class User implements Serializable {
    private String uid;
    private String username;
    private String password;

    public User() {
    }

    public User(String uid, String username, String password) {
        this.uid = uid;
        this.username = username;
        this.password = password;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    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;
    }
}

2.5. 編寫dao

package com.zqh.dao;

import com.zqh.domain.User;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author 漫路
 */
public interface UserMapper extends Mapper<User> {
}

2.6. 編寫service接口

package com.zqh.service;

import com.zqh.domain.User;

/**
 * @author 漫路
 */
public interface UserService {
    public User findByPrimaryKey(String uid);
    public void insertUser(User user);
}

2.6. 編寫service實現類

package com.zqh.service.impl;

import com.zqh.dao.UserMapper;
import com.zqh.domain.User;
import com.zqh.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 漫路
 */
@Service
@Transactional //開啓事務支持
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    public User findByPrimaryKey(String uid) {
        return userMapper.selectByPrimaryKey(uid);
    }

    public void insertUser(User user) {
        userMapper.insert(user);
    }
}

2.7. 編寫Spring配置類

1.配置註解
	1.1 掃描註解包
	1.2加載properties文件
	1.3 開啓註解事務支持
2.得到properties數據(實現類、@Value)
3.配置數據源DataSource
4.配置事務管理器(DataSourceTransactionManager)
package com.zqh.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;


/**
 * @author 漫路
 */
@Configuration
@ComponentScan(basePackages = {"com.zqh"})
@EnableTransactionManagement
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {
    // 4.2.4版本 固定配置
    @Bean
    public static PropertySourcesPlaceholderConfigurer create(){
        return  new PropertySourcesPlaceholderConfigurer();
    }

    //讀取數據庫相關配置
    @Value("${jdbc.driver}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    //數據源使用德魯伊鏈接池
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClass);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    // 開啓事務管理器
    @Bean
    @Resource
    public DataSourceTransactionManager txManager(DataSource dataSource){
        return  new DataSourceTransactionManager(dataSource);
    }

}

2.8. 編寫MyBatis配置類

1.配置session工廠,spring和MyBatis整合時,經過SqlSessionFactoryBean得到SqlSessionFactory
	SqlSessionFactoryBean只能加載mapper映射文件
	註解開發須要加載Mapper類,故須要對mapper進行掃描
2.配置映射掃描器
package com.zqh.config;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Spring整合MyBatis的配置類
 * @author 漫路
 */
// 聲明
@Configuration
public class MyBatisConfig {

    /**
     * 構建SessionFactory對象,SessionFactory能夠建立Session對象,最後使用Session操做數據庫
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    @Resource
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        // 1.經過工廠bean建立對象,最後須要調用 getObject()得到具體的對象
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 1.1 設置數據源
        factoryBean.setDataSource(dataSource);
        // 1.2 設置別名包掃描
        factoryBean.setTypeAliasesPackage("com.zqh.domain");
        // 1.3 全局配置:駝峯映射
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(config);

        // 2 插件配置
        // 2.1 分頁插件
        PageHelper pageHelper = new PageHelper();
        Properties pageProps = new Properties();
        pageProps.setProperty("dialect", "mysql");
        pageProps.setProperty("rowBoundsWithCount", "true");
        pageHelper.setProperties(pageProps);
        factoryBean.setPlugins(new Interceptor[]{pageHelper});

        // 3 經過工廠bean得到 sqlSessionFactory
        return factoryBean.getObject();
    }

    /**
     * 掃描Dao的包,查找各類XxxMapper接口,建立好UserMapper等對象存入到IOC的容器中
     *
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScanner() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.zqh.dao");
        return configurer;
    }

}

2.9. 編寫測試類

方式1: 整合Junit

package com.zqh;


import com.zqh.config.MyBatisConfig;
import com.zqh.config.SpringConfig;
import com.zqh.domain.User;
import com.zqh.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class, MyBatisConfig.class})
public class TestA {


    @Resource
    private UserService userService;

    @Test
    public void test01(){
        User user = new User("u001","張三丰","123");
        userService.insertUser(user);
        System.out.println("添加完畢");
    }
}
  • 運行

  • 控制檯打印

  • 數據庫

方式2: 手動建立工廠

package com.zqh;

import com.zqh.config.MyBatisConfig;
import com.zqh.config.SpringConfig;
import com.zqh.domain.User;
import com.zqh.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestB {
    public static void main(String[] args) {
        //1.建立工廠,設置兩個配置類
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class, MyBatisConfig.class);
        //2.從工廠獲取須要的對象
        UserService userService = applicationContext.getBean(UserService.class);
        //3.執行語句
        User user = new User("u800","zhangsan","123");
        userService.insertUser(user);
        System.out.println("添加完畢");
    }
}
  • 執行main方法

附錄pom文件

<properties>
        <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <!--spring core start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring core end-->

        <!--spring aop start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spirng aop end-->

        <!--spring aspects start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring aspects end-->

        <!--spring instrumentation start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring instrumentation end-->

        <!--spring messaging start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring messaging end-->

        <!--spring data access start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring data access end-->

        <!--spring web start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--spring web end -->

        <!--spring test start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <!--spring test end -->
        <!-- spring end -->


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>3.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

    </dependencies>
相關文章
相關標籤/搜索