溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot實現(xiàn)ORM操作MySQL的方法有哪些

發(fā)布時間:2022-02-21 09:28:22 來源:億速云 閱讀:118 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了SpringBoot實現(xiàn)ORM操作MySQL的方法有哪些的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇SpringBoot實現(xiàn)ORM操作MySQL的方法有哪些文章都會有所收獲,下面我們一起來看看吧。

使用mybatis框架操作數(shù)據(jù),在springboot框架中集成mybatis

使用步驟:

mybatis起步依賴:完成mybatis對象自動配置,對象放在容器中。

    <dependencies>
<!--        web起步依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        mybaitis起步依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
<!--        mysql驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--        測試-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

pom.xml指定把src/main/java目錄中的xml文件包含到classpath中。

    <build>

<!--        resources插件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

創(chuàng)建實體類Studnet

創(chuàng)建Dao接口StudentDao,創(chuàng)建一個查詢學生的方法。

/**
 * @Mapper :告訴MyBatis這是dao接口,創(chuàng)建此接口的代理對象,
 *      位置:在類的上面。
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

創(chuàng)建Dao接口對應的Mapper文件,xml文件,寫sql語句。

/**
 * @Mapper :告訴MyBatis這是dao接口,創(chuàng)建此接口的代理對象,
 *      位置:在類的上面。
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}
<?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.firewolf.dao.StudentDao">
<!--    定義sql語句-->
    <select id="selectById" resultType="com.firewolf.model.Student">
        select id,name,age from student where id=#{stuId}
    </select>
</mapper>

創(chuàng)建servlet層對象,創(chuàng)建StudentService接口和它的實現(xiàn)類。去調用dao對象的方法,完成數(shù)據(jù)庫的操作。

package com.firewolf.service;

public interface StudentService {
    Student queryStudent(Integer id);
}

package com.firewolf.service.impl;
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao studentDao;
    @Override
    public Student queryStudent(Integer id) {
        Student student=studentDao.selectById(id);
        return student;
    }
}

創(chuàng)建Controller對象,訪問Service。

@Controller
public class StudentController {
    @Resource
    private StudentService studentService;

    @RequestMapping("/student/query")
    @ResponseBody
    public String queryStudent(Integer id){
        Student student = studentService.queryStudent(id);
        return student.toString();
    }
}

寫application.properties文件。

配置數(shù)據(jù)庫的連接信息

server.port=9001
server.servlet.context-path=/orm
# 連接數(shù)據(jù)庫
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=991231gao

1.第一種方式:@Mapper

@Mapper:放在dao接口的上面,每個接口都需要使用這個注解。

/**
 * @Mapper :告訴MyBatis這是dao接口,創(chuàng)建此接口的代理對象,
 *      位置:在類的上面。
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

2.第二種方式 @MapperScan

/**
 * @MapperScan : 找到Dao接口和Mapper文件。
 *         basePackages:dao接口所在的包名
 * **/
@SpringBootApplication
@MapperScan(basePackages = {"com.firewolf.dao","com.firewolf.mapper"})
public class Application {

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

}

3.第三種方式:Mapper文件和Dao接口分開管理

現(xiàn)在把Mapper文件放在resources

  1. 在resources目錄中創(chuàng)建子目錄,例如mapper

  2. 把mapper文件放到mapper目錄中。

  3. 在application.properties文件中,指定mapper文件的目錄。

# 指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
# mybaitis的日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

在pom.xml中指定目錄,把resources目錄中的文件,編譯到目標目錄中。

<!--        resources插件-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

4.事務

spring框架中的事務

管理事務的對象:事務管理器(接口,接口有很多的實現(xiàn)類)。

例如:使用jdbc或mybatis訪問數(shù)據(jù)庫,使用事務管理器:DataSourceTransactionManager

聲明式事務:在xml配置文件或者使用注解說明事務控制的內容。

控制事務:隔離級別,傳播行為,超時時間。

事務處理方式

  • spring框架中的@Transactional

  • aspectj框架可以在xml配置文件中,聲明事務控制的內容。

springboot中使用事務:上面的兩種方式都可以。

  • 在業(yè)務方法的上面加入@Transactional,加入注解后,方法有事務功能了。

  • 明確在主啟動類的上面,加入@EnableTransactionManager。

@SpringBootApplication

@EnableTransactionManagement

@MapperScan(value="com.firewolf.dao")
public class Application {
   public static void main(String[] args) {
           SpringApplication.run(Application.class, args);
   }
}

例子:

/**
 * @Transactional: 表示方法的有事務支持
 *       默認:使用庫的隔離級別, REQUIRED 傳播行為; 超時時間  -1
 *       拋出運行時異常,回滾事務
 */
@Transactional
@Override
public int addStudent(Student student) {
    System.out.println("業(yè)務方法addStudent");
    int rows  =  studentDao.insert(student);
    System.out.println("執(zhí)行sql語句");

    //拋出一個運行時異常, 目的是回滾事務
    //int m   = 10 / 0 ;

    return rows;
}

關于“SpringBoot實現(xiàn)ORM操作MySQL的方法有哪些”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“SpringBoot實現(xiàn)ORM操作MySQL的方法有哪些”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI