AdSense

網頁

2017/12/18

Mybatis Spring 連線資料庫設定

在Spring使用Mybatis的設定方法如下,本篇使用Maven來加入所需的jar

本篇所連線的資料庫為MySQL 5.x

首先在Maven的pom.xml加入Spring MVC,Spring JDBCSpring TransactionMybatis及JDBC driver(範例為MySQL Connector/J)的jar如下,本篇是使用SpringMVC,而連線的資料庫為MySQL 5.7

<!-- SpringMVC -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.3.14.RELEASE</version>
</dependency>
<!-- Mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.5</version>
</dependency>

<!-- MySQL jdbc driver -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.40</version>
</dependency>

接著在Maven的pom.xml加入mybatis-spring的jar如下,此為整合Spring及Mybatis所需要的jar。

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>

以上是所需要的函式庫。


接著設定Spring的配置檔,注意<beans>的shema命名空間及xsi schema位置設定。

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
  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.xsd
                      http://mybatis.org/schema/mybatis-spring 
                      http://mybatis.org/schema/mybatis-spring.xsd">
        
  <!-- MySQL jdbc dataSource config -->
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" /><!-- MySQL 8的driverClassName 為com.mysql.cj.jdbc.Driver -->
    <property name="url" value="jdbc:mysql://localhost:3306/mydatabase" />
    <property name="username" value="matthung" />
    <property name="password" value="12345" />
  </bean>      
        
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configuration">
      <!-- MyBatis other config settings 設定其他MyBatis參數 (mybatis-spring 1.3以上)-->
      <bean class="org.apache.ibatis.session.Configuration">
        <property name="defaultStatementTimeout" value="3"/><!-- 設定等待資料庫回應的時間(單位:秒) -->
        <property name="localCacheScope" value="STATEMENT"/><!-- 設定local cache作用範圍 -->
      </bean>
    </property>
  </bean>
  
  <mybatis:scan base-package="idv.matthung.mapper" factory-ref="sqlSessionFactory"/>
  
</beans> 

若要設定MyBatis的其他參數,可在SqlSessionFactoryBeanconfiguration屬性設定(mybatis-spring 1.3版本以後才支援直接在Spring配置檔設定MyBatis的參數,在之前要另外指定mybatis-config.xml)。

上面設定中利用<mybatis:scan base-package="idv.matthung.mapper">將存取資料庫的Mybatis mapper介面位置設在idv.matthung.mapper

接著在idv.matthung.mapper下新增Mapper介面,例如idv.matthung.mapper.UserInfoMapper,與資料庫中的USER_INFO資料表對應。Mapper介面用來定義存取資料庫的方法,而方法的實作(SQL查詢語句)會定義在Mapper的xml檔。

package idv.matthung.mapper;
import java.util.List;
import idv.matthung.model.UserInfo;

public interface UserInfoMapper {
  
  public List<UserInfo> getAll();

}

Mybatis Mapper的xml檔預設會放在與介面同樣的classpath下,所以接著在idv.matthung.mapper下新增對應UserInfoMapper介面的xml檔,檔案名稱與介面相同,所以是UserInfoMapper.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="idv.matthung.mapper.UserInfoMapper">
  <resultMap id="userInfoResultMap" type="idv.matthung.model.UserInfo">
    <id property="userId"           column="USER_ID"      javaType="Integer"  jdbcType="INTEGER"/>
    <result property="email"        column="EMAIL"        javaType="String"   jdbcType="VARCHAR"/>
    <result property="password"     column="PASSWORD"     javaType="String"   jdbcType="VARCHAR"/>
    <result property="name"         column="NAME"         javaType="String"   jdbcType="VARCHAR"/>
  </resultMap>
  
  <select id="getAll" resultMap="userInfoResultMap">
    SELECT * FROM USER_INFO
  </select>
</mapper>

上面UserInfoMapper介面getAll()方法實際上會執行UserInfoMapper.xml中對應的id名稱中的SQL,也就是<select id="getAll" ... >,查詢後會根據resultMap的設定將資料表的資料塞入model UserInfo物件。

UserInfo model類別

package idv.matthung.model;

public class UserInfo {
  private Integer userId;
  private String email;
  private String password;
  private String name;
  
  public Integer getUserId() {
    return userId;
  }
  public void setUserId(Integer userId) {
    this.userId = userId;
  }
  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  
}

以上即為Spring搭配Mybatis的設定,在程式中使用範例如下。

@Service
public class UserInfoServiceImpl implements UserInfoService{
  
  @Autowired
  UserInfoMapper userInfoMapper;
  
  public void qetAllUserInfos() {
    // ...
    List<UserInfo> userInfoList = userInfoMapper.getAll(); // 呼叫UserInfoMapper.getAll()對應的SQL
    // ...
  }

}

如果要更改xml的位置,則在Spring配置檔的SqlSessionFactoryBean bean加入mapperLocations屬性如下

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath*:idv/matthung/mapper/xml/**/*.xml" />
</bean>

上面設定將會讀取idv.matthung.mapper.xml package及其子目錄中的全部Mapper xml檔。


除了用xml mapper,也可以直接在Mapper介面使用Mapper annotation來設定SQL,例如上面UserInfoMapper可改為如下,如此就不需要xml的mapper檔了。不過xml mapper的功能比較完整,所以還是使用xml mapper來設定比較好。

package idv.matt.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import idv.matthung.model.UserInfo;

public interface UserInfoMapper {
  @Results({
    @Result(property = "userId", column = "USER_ID"),
    @Result(property = "password", column = "PASSWORD"),
    @Result(property = "email", column = "EMAIL"),
    @Result(property = "name", column = "NAME")
  })
  
  @Select("SELECT * FROM USER_INFO")
  public List getAll();
}

如果覺得文章有幫助的話還幫忙點個Google廣告,感恩。


參考:

沒有留言:

AdSense