1. 程式人生 > >建立一個Spring Boot+Mybatis+Oracle的Web專案

建立一個Spring Boot+Mybatis+Oracle的Web專案

最近學習Spring Boot,剛好複習下Mybatis,因為現在用的是Hibernate,Mybatis已經有兩年沒用過了。

首先我用的資料庫是Oracle.

1、New Project 

2、建立完成後的目錄結構如下:(如果有的同學的資料庫使用的是mysql的話,可以勾選上面的mysql,Spring Boot會自動新增我們spring和mysql的依賴,當時我們自己手動新增也可以。)

3、開啟我們的pom.xml檔案,新增我們所用的依賴jar包

 我們此專案只需要新增兩個依賴jar包

一個是Oracle驅動包(此處的Oracle驅動包是我本地的jar包,因為Oracle授權問題,mavem不提供oracleq驅動包了)

一個是C3P0連線池jar包

<dependency>
   <groupId>com.oracle</groupId>
   <artifactId>ojdbc14</artifactId>
   <version>10.2.0.1</version>
   <scope>provided</scope>
</dependency>

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>

4、資料庫DDL語句:

CREATE TABLE STUDENT
(
  SID   NUMBER(10) NOT NULL PRIMARY KEY,
  SNAME VARCHAR2(255 CHAR),
  SEX   VARCHAR2(255 CHAR)
)

create sequence STUDENT_SEQUENCE
minvalue 1
maxvalue 999999999999999999999999999
start with 21
increment by 1
cache 20;

一個是建立student表語句,一個是為該表建立一個序列語句,序列為了讓表的自增主鍵使用。如果使用的是mysql資料庫的話,可以設定主鍵自增,則不需要建立序列。

5、在application.properties中配置我們的專案資訊

jdbc.driver = oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@127.0.0.1:1521:ORCL
jdbc.username = mw_app
jdbc.password = app

server.port = 8083

server.servlet.context-path=/spring-mybatis

6、在resource目錄下建立我們的mybatis配置檔案,mybatis-config.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--  是否允許主鍵生成策略 -->
        <setting name="useGeneratedKeys" value="true"/>

        <!-- 是否使用駝峰轉換 -->
        <setting name="mapUnderscoreToCamelCase" value="true" />

        <!-- 是否允許使用列標籤替換列名 -->
        <setting name="useColumnLabel" value="true" />

    </settings>
    
</configuration>

7、建立我們的spring配置檔案,applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- spring掃描註解的包路徑 -->
    <context:component-scan base-package="com.spring.springmybatis" />
    <!-- spring載入properties檔案的路徑 -->
    <context:property-placeholder location="classpath:config/application.properties"/>

    <!-- C3P0連線池配置 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="autoCommitOnClose" value="true" />
        <property name="acquireRetryAttempts" value="3" />
        <property name="initialPoolSize" value="10" />
        <property name="checkoutTimeout" value="2000" />
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
    </bean>

    <!-- sessionFactory配置 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 載入資料來源Bean -->
        <property name="dataSource" ref="dataSource" />
        <!-- 載入mybatis的配置檔案的路徑 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- mapper檔案所在的路徑 -->
        <property name="mapperLocations" value="classpath:mapper/mapper-*.xml" />
        <!-- mybatis使用使用類別名的類所在的包路徑 -->
        <property name="typeAliasesPackage" value="com.spring.springmybatis.entity" />
    </bean>

    <!-- 配置Spring掃描mybatis的資訊 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sessionFactory" />
        <!-- 需要掃描的Dao包路徑 -->
        <property name="basePackage" value="com.spring.springmybatis.dao" />
    </bean>
</beans>

 

專案的配置檔案我們已經配置的差不多了,對配置不明白的同學可以檢視mybatis的中文官方網站 http://www.mybatis.org/mybatis-3/zh/index.html   或者在下面留言。

下面我們開始編碼階段:

8、根據資料庫表名建立我們的實體類Student.java,程式碼如下:

package com.spring.springmybatis.entity;

public class Student {

    private Integer sid;
    private String sname;
    private String sex;

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Student() {
    }

    public Student(String sname, String sex) {
        this.sname = sname;
        this.sex = sex;
    }


}

9、我們建立我們的Dao介面,並建立增刪改查方法;程式碼如下:

package com.spring.springmybatis.dao;

import com.spring.springmybatis.entity.Student;

import java.util.List;

public interface StudentDao {

    /**
     * 根據ID查詢學生資訊
     * @param id
     * @return Student物件
     */
    public Student queryStudent(int id);

    /**
     * 查詢學生列表
     * @return
     */
    public List<Student> queryStudentList();

    /**
     * 新增學生資訊
     * @param student
     * @return
     */
    public int addStudent(Student student);

    /**
     * 修改學生資訊
     * @param student
     * @return
     */
    public int modifyStudent(Student student);

    /**
     * 根據ID刪除學生資訊
     * @param id
     * @return
     */
    public int deleteStudent(int id);

}

10、因為spring會為mybatis宣告的dao介面生成的實現類,所以我們不需要手動為我們定義的Dao介面編寫實現類,我們只需要編寫對應的mapper配置檔案,我們建立的mapper配置檔案如下(這裡的路徑需要和spring配置檔案中mapperLocation指定的路徑一致):

mapper-student.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="com.spring.springmybatis.dao.StudentDao">

    <select id="queryStudent" resultType="Student" >
      SELECT SID,SNAME,SEX,GID
      FROM STUDENT
      WHERE SID = #{id}
    </select>
    
    <select id="queryStudentList" resultType="Student">
        SELECT *
        FROM STUDENT
    </select>

    <insert id="addStudent" parameterType="com.spring.springmybatis.entity.Student">
        <selectKey keyProperty="sid" resultType="int" order="BEFORE">
            select STUDENT_SEQUENCE.NEXTVAL
            FROM DUAL
        </selectKey>
        INSERT INTO STUDENT (sid,sname,sex)
        values (#{sid},#{sname},#{sex})
    </insert>

    <update id="modifyStudent" parameterType="Student" >
        UPDATE STUDENT
        <set>
            <if test="sname != null">sname = #{sname}</if>
            <if test="sex != null">sname = #{sex}</if>
        </set>
        WHERE SID = #{sid}
    </update>

    <delete id="deleteStudent" parameterType="int">

        DELETE FROM STUDENT
        WHERE SID = #{sid}

    </delete>

</mapper>

11、此時我們的Dao層已經編寫完成了,為了和真實專案保持一直,我們這裡編寫一下service層的程式碼,讓service層呼叫我們的dao層介面去操作資料庫,StudentService.java程式碼如下:

package com.spring.springmybatis.service;

import com.spring.springmybatis.entity.Student;

import java.util.List;

public interface StudentService {
    /**
     * 根據ID查詢學生資訊
     * @param id
     * @return Student物件
     */
    public Student queryStudent(int id);

    /**
     * 查詢學生列表
     * @return
     */
    public List<Student> queryStudentList();

    /**
     * 新增學生資訊
     * @param student
     * @return
     */
    public int addStudent(Student student);

    /**
     * 修改學生資訊
     * @param student
     * @return
     */
    public int modifyStudent(Student student);

    /**
     * 根據ID刪除學生資訊
     * @param id
     * @return
     */
    public int deleteStudent(int id);

}

其實現類StudentServiceImpl.java程式碼如下:

package com.spring.springmybatis.service.impl;

import com.spring.springmybatis.dao.StudentDao;
import com.spring.springmybatis.entity.Student;
import com.spring.springmybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    public Student queryStudent(int id) {
        System.out.println("執行查詢學生資訊方法");
        return studentDao.queryStudent(id);
    }

    @Override
    public List<Student> queryStudentList() {
        System.out.println("執行查詢學生列表資訊的方法");
        return studentDao.queryStudentList();
    }

    @Override
    public int addStudent(Student student) {
        System.out.println("執行新增學生資訊的方法");
        return studentDao.addStudent(student);
    }

    @Override
    public int modifyStudent(Student student) {
        System.out.println("執行修改學生資訊的方法");
        return studentDao.modifyStudent(student);
    }

    @Override
    public int deleteStudent(int id) {
        System.out.println("執行刪除學生資訊的方法");
        return studentDao.deleteStudent(id);
    }
}

12、下面我們為service層程式碼建立Junit測試方法,我們的Junit測試類程式碼如下:

package com.spring.springmybatis.service;

import com.spring.springmybatis.entity.Student;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class StudentServiceTest {

    @Autowired
    private StudentService studentService;

    @Test
    @Ignore
    public void addStudent() {
        Student student = new Student("小紅","女");
        assertEquals(1,studentService.addStudent(student));
    }

    @Test
    @Ignore
    public void queryStudent() {
        Student student  = studentService.queryStudent(1);
        System.out.println(student.getSname());
    }

    @Test
    public void queryStudentList() {
        List<Student> studentList = studentService.queryStudentList();
        studentList.forEach(e -> System.out.println(e.getSname()));
    }

    @Test
    @Ignore
    public void modifyStudent() {
        Student student = new Student();
        student.setSname("眉莊");
        student.setSid(1);
        assertEquals(1,studentService.modifyStudent(student));
    }

    @Test
    @Ignore
    public void deleteStudent() {
        assertEquals(1,studentService.deleteStudent(1));
    }
}

我們可以把@Ignore註解去掉,挨個進行測試

13、因為我們是Web專案,所以我把對應的Controller程式碼也加上了,StudentController.java程式碼如下:

package com.spring.springmybatis.controller;

import com.spring.springmybatis.entity.Student;
import com.spring.springmybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/queryStudent")
    public Student queryStudent(int id) {
        return studentService.queryStudent(id);
    }

    @RequestMapping("/queryStudentList")
    public List<Student> queryStudentList() {
        return studentService.queryStudentList();
    }

    @RequestMapping("/addStudent")
    public int addStudent(Student student) {
        return studentService.addStudent(student);
    }

    @RequestMapping("/modifyStudent")
    public int modifyStudent(Student student) {
        return studentService.modifyStudent(student);
    }

    @RequestMapping("/deleteStudent")
    public int deleteStudent(int id) {
        return studentService.deleteStudent(id);
    }

}

14、我們Spring Boot啟動檔案程式碼如下:

package com.spring.springmybatis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;

import java.util.Arrays;

@ImportResource(value = {"classpath:applicationContext.xml"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SpringMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringMybatisApplication.class, args);
    }
}

15、我們通過執行Main方法啟動我們的專案,在瀏覽器輸入地址進行訪問,可以看到正常返回資料

 

因為Spring Boot是剛接觸的,聽說可以不用配置建立專案,很多地方都不知道怎麼用,所以可能用到的技術比較老,後面接觸多了再重新寫一遍少用配置的吧!

我把做完的專案結構發一下: