1. 程式人生 > >springboot+mybatis+oracle 整合

springboot+mybatis+oracle 整合

本文只是保證服務能讀到資料,些許部分可能不詳細請見諒,本次使用scott.emp表進行測試。

首先去官網生成springboot服務https://start.spring.io/,或者用sts本地生成,這裡不多做介紹。

檔案結構:

下面貼出相關程式碼;

pom.xml(部分引用無用,可以自行去除比如反向工程,快取,外掛),這裡說明一下oracle6 引入可能會失敗,翻牆也不行,映象我沒有進行嘗試,直接從maven中央倉庫下載的放到本地庫中了。

<?xml version="1.0" encoding="UTF-8"?>
<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>come.demo.SpringBootMyBatis</groupId>
	<artifactId>SpringBootMyBatis</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>SpringBootMyBatis</name>
	<description>SpringBootMyBatis</description>

	<!-- lookup parent from repository -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath />
	</parent>
		
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!--ehcache-->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.10.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc6 -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.5</version>
		</dependency>

		<!-- SpringBoot - MyBatis 逆向工程 -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.3</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-maven-plugin</artifactId>
					<!--<configuration>
						<maimClass>com.demo.Application</maimClass>
					</configuration>-->
					<executions>
						<execution>
							<goals>
								<goal>repackage</goal>
							</goals>
						</execution>
					</executions>
				</plugin>
			<!-- Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<testFailureIgnore>true</testFailureIgnore>
				</configuration>
			</plugin>

			<!-- Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1: -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<verbose>true</verbose>
					<fork>true</fork>
					<executable>${env.JAVA_HOME}/bin/javac</executable>
				</configuration>
			</plugin>
		</plugins>
		<defaultGoal>compile</defaultGoal>
	</build>


</project>

application.properties:

server.port=8081
server.address=127.0.0.1
server.contextPath=/

spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
spring.datasource.username=fc
spring.datasource.password=fc
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
DataSourceConfig(連線配置):
package com.demo;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
//指定掃描的mapper介面所在的包
@MapperScan(basePackages = "com.demo", sqlSessionFactoryRef = "DBDataSqlSessionFactory")
public class DataSourceConfig {
	@Bean(name = "DBDataSource")	
	@ConfigurationProperties(prefix="spring.datasource") //告訴自動載入配置的屬性
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "DBDataSqlSessionFactory")
	public SqlSessionFactory  sqlSessionFactory(@Qualifier("DBDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "DBDataTransactionManager")
	public DataSourceTransactionManager transactionManager(@Qualifier("DBDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "DBDataSqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(
			@Qualifier("DBDataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
Employee:
package com.demo.entity;

import java.util.Date;
import java.util.List;

//使用資料庫系統自帶的資料表,對應scott.emp表
public class Employee {
	private Integer EMPNO;   //員工號
	private String  ENAME;   //員工名
	private String  JOB;     //工種
	private Integer MGR;     //上級
	private Date    HIREDATE;//入職日期
	private double  SAL;     //工資
	private double  COMM;    //獎金
	private Integer DEPTNO;  //部門號


	public String toString()
	{		
		String info = String.format("EMPNO[%d], ENAME[%s], JOB[%s], MGR[%d], HIREDATE[%tF], SAL[%.2f], COMM[%.2f], DEPTNO[%d]", EMPNO, ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO);
		return info;
	}

	public static void Print(List<Employee> empList)
	{
		int count = empList.size();	
		String format = String.format("Employee[%%%dd]: %%s", String.valueOf(count).length());
		String info = String.format("%5s, %7s, %10s, %4s, %10s, %7s, %7s, %s","EMPNO", "ENAME","JOB","MGR","HIREDATE","SAL","COMM","DEPTNO");
		System.out.println(String.format(format, count,info));	
		for(int i=0;i<count;i++){
			Employee emp = empList.get(i);
			info = String.format("%5d, %7s, %10s, %4d, %tF, %7.2f, %7.2f, %d", emp.EMPNO, emp.ENAME,emp.JOB,emp.MGR,emp.HIREDATE,emp.SAL,emp.COMM,emp.DEPTNO);
			System.out.println(String.format(format, i,info));	
		}	
		return;
	}

	public Integer getEMPNO() {
		return EMPNO;
	}

	public void setEMPNO(Integer eMPNO) {
		EMPNO = eMPNO;
	}

	public String getENAME() {
		return ENAME;
	}

	public void setENAME(String eNAME) {
		ENAME = eNAME;
	}

	public String getJOB() {
		return JOB;
	}

	public void setJOB(String jOB) {
		JOB = jOB;
	}

	public Integer getMGR() {
		return MGR;
	}

	public void setMGR(Integer mGR) {
		MGR = mGR;
	}

	public Date getHIREDATE() {
		return HIREDATE;
	}

	public void setHIREDATE(Date hIREDATE) {
		HIREDATE = hIREDATE;
	}

	public double getSAL() {
		return SAL;
	}

	public void setSAL(double sAL) {
		SAL = sAL;
	}

	public double getCOMM() {
		return COMM;
	}

	public void setCOMM(double cOMM) {
		COMM = cOMM;
	}

	public Integer getDEPTNO() {
		return DEPTNO;
	}

	public void setDEPTNO(Integer dEPTNO) {
		DEPTNO = dEPTNO;
	}


}

DataMapper:
package com.demo.mapper;

import java.util.List;

import com.demo.entity.Employee;
import org.apache.ibatis.annotations.Param;


//對映Sql,定義介面
public interface DataMapper {	

	//查詢。@Param對應引數屬性註解,There is no getter for property named 'xx' in 'class java.lang.Integer
	List<Employee> test_query(@Param("EMPNO")Integer EMPNO);

	//插入
	void test_insert(Employee employee);

	//更新
	void test_update(@Param("EMPNO")Integer EMPNO, @Param("COMM")double COMM);

	//刪除
	void test_delete(Integer EMPNO);

	//批量插入
	void test_multi_insert(List<Employee> results);

	//批量查詢
	List<Employee> test_multi_query(int[] DEPTNOArr);

	//批量刪除
	void test_multi_delete(List<Integer> EMPNOList);
}
SQLTest(抄錄資料 忘記從哪拷貝的了):

SQLTest.run()使用@Autowired註解,這樣在專案啟動時候,就自動載入運行了

package com.demo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.demo.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo.mapper.DataMapper;

@Component
public class SQLTest {

	@Autowired
	DataMapper dataMapper;

	//自動載入,程式啟動時候就執行啦。。。。
	@Autowired
	public void run() {
		test_query();

		test_insert();
		test_query();

		test_update();
		test_query();

		test_multi_query();

		test_multi_insert();
		test_multi_query();		

		test_delete();
		test_query();

		test_multi_delete();
		test_multi_query();

		/*test_exe_procedure(true);
		test_exe_procedure(false);*/
	}

	private void test_query()
	{
		System.out.println("test_query...");	
		Integer EMPNO =7788;
		List<Employee> empList =dataMapper.test_query(EMPNO);
		Employee.Print(empList);
		return;
	}

	private void test_insert()
	{
		System.out.println("test_insert...");	
		Employee emp = new Employee();
		emp.setEMPNO(7979);
		emp.setENAME("ENAME");
		emp.setJOB("JOB");
		emp.setMGR(7566);
		emp.setHIREDATE(new Date());
		emp.setSAL(8799.76);
		emp.setCOMM(235.65);
		emp.setDEPTNO(20);
		dataMapper.test_insert(emp);
	}

	private void test_update()
	{
		System.out.println("test_update...");	
		dataMapper.test_update(7979, 555.25);
	}

	private void test_delete()
	{
		System.out.println("test_delete...");
		dataMapper.test_delete(7979);
	}

	private void test_multi_insert()
	{
		System.out.println("test_multi_insert...");	
		Employee emp1 = new Employee();
		emp1.setEMPNO(7980);
		emp1.setENAME("ENAME1");
		emp1.setJOB("JOB1");
		emp1.setMGR(7566);
		emp1.setHIREDATE(new Date());
		emp1.setSAL(8799.76);
		emp1.setCOMM(235.65);
		emp1.setDEPTNO(30);

		Employee emp2 = new Employee();
		emp2.setEMPNO(7981);
		emp2.setENAME("ENAME2");
		emp2.setJOB("JOB2");
		emp2.setMGR(7566);
		emp2.setHIREDATE(new Date());
		emp2.setSAL(8799.76);
		emp2.setCOMM(235.65);
		emp2.setDEPTNO(30);

		Employee emp3 = new Employee();
		emp3.setEMPNO(7979);
		emp3.setENAME("ENAME");
		emp3.setJOB("JOB2");
		emp3.setMGR(7566);
		emp3.setHIREDATE(new Date());
		emp3.setSAL(8799.76);
		emp3.setCOMM(235.65);
		emp3.setDEPTNO(20);

		List<Employee> empList = new ArrayList<Employee>();
		empList.add(emp1);
		empList.add(emp2);
		empList.add(emp3);
		dataMapper.test_multi_insert(empList);
	}

	private void test_multi_query()
	{
		System.out.println("test_multi_query...");	
		int[] DEPTNOArr = { 20, 30 };
		List<Employee> empList  =  dataMapper.test_multi_query(DEPTNOArr);
		Employee.Print(empList);
		return;		
	}

	private void test_multi_delete()
	{
		System.out.println("test_multi_delete...");	
		List<Integer> EMPNOList = new ArrayList<Integer>();		
		EMPNOList.add(7980);
		EMPNOList.add(7981);
		dataMapper.test_multi_delete(EMPNOList);
		return;		
	}

}

dbMapper.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" >
<!-- 對映檔案,對映到對應的SQL介面 -->
<mapper namespace="com.demo.mapper.DataMapper">

	<!--返回的結果集,用於關聯實體類屬性和資料庫欄位 -->
	<!--如果實體類屬性和資料庫屬性名保持一致,就不需要javaType和jdbcType(必須大寫)屬性 -->
	<resultMap id="Employee_resultMap" type="com.demo.entity.Employee">
		<result column="EMPNO" property="EMPNO" javaType="java.lang.Integer" jdbcType="INTEGER" />
		<result column="ENAME" property="ENAME" javaType="java.lang.String" jdbcType="VARCHAR" />
		<result column="JOB" property="JOB" javaType="java.lang.String" jdbcType="VARCHAR" />
		<result column="MGR" property="MGR" javaType="java.lang.Integer" jdbcType="INTEGER" />
		<result column="HIREDATE" property="HIREDATE" javaType="java.util.Date" jdbcType="DATE"/>
		<result column="SAL" property="SAL" javaType="java.lang.Double" jdbcType="DOUBLE" />
		<result column="COMM" property="COMM" javaType="java.lang.Double" jdbcType="DOUBLE" />
		<result column="DEPTNO" property="DEPTNO" javaType="java.lang.Integer" jdbcType="INTEGER" />
	</resultMap>
	
	<!-- 查詢資料 -->
	<!-- 入參定義:在介面定義中使用@Param註解(單參/多參都可使用) -->
	<!-- 語句末尾不能有分號:ORA-00911: invalid character -->
	<select id="test_query" resultMap="Employee_resultMap">
		select t.EMPNO, t.ENAME, t.JOB, t.MGR, t.HIREDATE, t.SAL, t.COMM, t.DEPTNO from scott.emp t where 1=1 
		<if test="EMPNO != null">
			and t.EMPNO &gt;= #{EMPNO}
		</if>	
		order by t.EMPNO
	</select>

	<!-- 插入資料 -->
	<!-- 入參定義:實體類,會自動解析屬性到對應的值-->
	<insert id="test_insert" parameterType="com.demo.entity.Employee">
		insert into scott.emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
		values (#{EMPNO}, #{ENAME}, #{JOB}, #{MGR}, #{HIREDATE}, #{SAL}, #{COMM}, #{DEPTNO})
	</insert>
	
	<!-- 更新資料 -->
	<!-- 入參定義:在介面定義中使用@Param註解(多參情況,只能使用這種形式) -->
	<update id="test_update">
		UPDATE scott.emp SET COMM = #{COMM}
		WHERE EMPNO = #{EMPNO}
	</update>
	
	<!-- 刪除資料 -->
	<!-- 入參定義:parameterType指定輸入引數(單參情況,亦可@Param註解) -->
	<delete id="test_delete" parameterType="java.lang.Integer">
		DELETE FROM scott.emp t WHERE t.EMPNO =#{EMPNO}
	</delete>

	<!-- 批量查詢 -->
	<!-- 入參定義:使用[]陣列array -->
	<select id="test_multi_query"  parameterType="int[]" resultMap="Employee_resultMap">
		select t.EMPNO, t.ENAME, t.JOB, t.MGR, t.HIREDATE, t.SAL, t.COMM, t.DEPTNO from scott.emp t where t.DEPTNO in
		<!-- arr:array中的具體值 -->
		<foreach collection="array" item="arr" index="no" open="(" separator="," close=")">  
            #{arr}  
        </foreach>
	</select>	
	
	<!-- 批量插入 -->
	<!-- 入參定義:使用List集合物件 -->
	<insert id="test_multi_insert" parameterType="java.util.List">
		merge into scott.emp r 
		    <!-- insert 和update中所有的資料都需要從using中獲取 -->
			using(
			<!-- item:list中的具體物件 -->
			<foreach collection="list" index="index" item="item" open="" close="" separator="union">
				select
					#{item.EMPNO,jdbcType=INTEGER} as EMPNO,
					#{item.ENAME,jdbcType=VARCHAR} as ENAME,
					#{item.JOB,jdbcType=VARCHAR} as JOB,
					#{item.MGR,jdbcType=INTEGER} as MGR,
					#{item.HIREDATE,jdbcType=DATE} as HIREDATE,
					#{item.SAL,jdbcType=DOUBLE} as SAL,
					#{item.COMM,jdbcType=DOUBLE} as COMM,
					#{item.DEPTNO,jdbcType=INTEGER} as DEPTNO
				from dual
			</foreach>
			) tmp 
			<!-- on後面的括弧不能省 -->
			on ( tmp.EMPNO = r.EMPNO)
		when matched THEN
			update set
			<!-- ORA-38104: 在on條件中的列是不可以更新的 -->
			<!-- r.EMPNO = tmp.EMPNO, -->
			r.ENAME = tmp.ENAME,
			r.JOB = tmp.JOB,
			r.MGR = tmp.MGR,
			r.HIREDATE = tmp.HIREDATE,
			r.SAL = tmp.SAL,
			r.COMM = tmp.COMM,
			r.DEPTNO = tmp.DEPTNO
		when not matched THEN
			insert
			<trim prefix="(" suffix=")" suffixOverrides=",">
				EMPNO,
				ENAME,
				JOB,
				MGR,
				HIREDATE,
				SAL,
				COMM,
				DEPTNO
			</trim>
			<trim prefix="values (" suffix=")" suffixOverrides=",">
				tmp.EMPNO,
				tmp.ENAME,
				tmp.JOB,
				tmp.MGR,
				tmp.HIREDATE,
				tmp.SAL,
				tmp.COMM,
				tmp.DEPTNO
			</trim>
	</insert>

	<!-- 批量刪除 -->
	<delete id="test_multi_delete">
		<!-- delete from emp where empno in(7980,7981) --> 
		delete from scott.emp t where t.empno in
		 <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
			  #{item}  
 			</foreach>
	</delete>

</mapper>
HelloWorldController:
package com.demo.controller;

import com.demo.mapper.DataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/hello")
public class HelloWorldController {
    @Autowired
    DataMapper dataMapper;

    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser( ){

        return dataMapper.test_query(1);
    }
}