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

最后  http://localhost:8081/hello/all  看一下效果吧。

猜你喜欢

转载自blog.csdn.net/a290450134/article/details/82773394
今日推荐