MyBatis
MyBatis 是灵活的 SQL 映射, 不想 Hibrnate 是纯的 ORM, 个人还是比较写 SQL 语句, 不喜欢纯的 ORM.
首先引入 Maven 依赖.
添加 mybatis 配置, 包括 DAO, Model, XML映射文件.
在 config 包下边创建一个 MybatisConfig.java
package com.example.demo.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
@Configuration
@MapperScan("com.example.demo.**.dao") // 扫描DAO
public class MybatisConfig {
@Autowired
private javax.sql.DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage("com.example.demo.**.model");
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml"));
return sessionFactory.getObject();
}
}
添加数据源, 在 application.yml 中
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysql
username: root
password: root
工具生成 Model, DAO, XML
Model = 数据库中的 entity, 也就是数据库中的表.
DAO = Mapper, 对数据库中的持久化操作, 与 XML 相对应. xml(写SQL语句, 有一个id), DAO 针对这个 id 有对应的方法.
Mybatis Generator 和 MyBatis Plus 都可以做到. 我这里边用 MyBatis Plus 来举例:
Original: https://www.cnblogs.com/moveofgod/p/14618770.html
Author: 神之一招
Title: 02 MyBatis & Druid
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/543085/
转载文章受原作者版权保护。转载请注明原作者出处!