本文主要介紹一個基於Spring Boot 2.x,mySQL和myBatis完成簡單的用Web操做數據庫的demo程序,而後採用的是全註解方式實現的,徹底不須要xml配置(後續會在寫一個全xml配置demo)。主要支持如下功能:
(1) 數據庫自動建表,如本例中的user表。
(2) 數據庫CRUD(create read update delete)操做。
(3) 經過http get操做user表。java
環境準備:
(1) IDEA(建議使用Ultimate版本,會自帶經過IDEA操做database的功能)
(2) MySQL
(3) Maven + JDK8mysql
項目目錄結構:git
\---main +---java | \---hello | | MainApplication.java | | | +---bean | | User.java | | | +---config | | MyBatisMapperScannerConfig.java | | MybatisTableConfig.java | | | +---controller | | UserController.java | | | +---dao | | UserDao.java | | | \---service | UserService.java | \---resources application.properties sql.txt pom.xml
數據庫和用戶表:
默認的使用數據庫是MySQL下的sakila,這個能夠經過修改application.properties裏的配置更改本地數據庫名。
user表用的是相似下面的SQL語句建立的:web
CREATE TABLE `user` ( `id` int(13) NOT NULL AUTO_INCREMENT, `name` varchar(33) DEFAULT NULL, `age` int(3) DEFAULT NULL, `money` double DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
本demo採用了自動建表的方式,即在Spring Boot啓動的時候會自動根據
(1) application.properties裏的配置
(2) config/MyBatisMapperScannerConfig.java和config/ MybatisTableConfig.java
(3) bean/user.json裏面設置的註解
經過第三方框架mybatis.actable完成表的自動建立功能。
具體內容能夠參考https://blog.csdn.net/qq_43670895/article/details/83986715spring
須要注意的是,使用第三方框架mybatis.actable的時候如下四個依賴項都須要引入:sql
<dependency> <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> <artifactId>mybatis-enhance-actable</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency>
pom.xml pom中須要添加boot-starter-web的依賴,MySQL鏈接的依賴,myBatis的依賴,以及第三方框架mybatis.actable須要的四個依賴。數據庫
<?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>MybatisDemo</groupId> <artifactId>MybatisDemo</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> <artifactId>mybatis-enhance-actable</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
配置 application.properties,鏈接本地MySQL數據庫以及自動建表配置apache
server.port=8333 # 數據庫爲sakila spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sakila?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 自動建表的配置,結合hello.config能夠自動建立user的表 mybatis.table.auto=create mybatis.model.pack=hello.bean mybatis.database.type=mysql
MyBatisMapperScannerConfig.java 自動建表配置類json
package hello.config; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @AutoConfigureAfter(MybatisTableConfig.class) public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{ MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.example.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*"); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); return mapperScannerConfigurer; } }
MybatisTableConfig.java 自動建表配置類,須要配置自動建表的User類路徑hello.bean.*mybatis
package hello.config; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @Configuration @ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"}) public class MybatisTableConfig { @Value("${spring.datasource.driver-class-name}") private String driver; @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Bean public PropertiesFactoryBean configProperties() throws Exception{ PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); propertiesFactoryBean.setLocations(resolver.getResources("classpath*:application.properties")); return propertiesFactoryBean; } @Bean public DruidDataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaxActive(30); dataSource.setInitialSize(10); dataSource.setValidationQuery("SELECT 1"); dataSource.setTestOnBorrow(true); return dataSource; } @Bean public DataSourceTransactionManager dataSourceTransactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource()); return dataSourceTransactionManager; } @Bean public SqlSessionFactoryBean sqlSessionFactory() throws Exception{ SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("hello.bean.*"); return sqlSessionFactoryBean; } }
User.java
用戶類User,基於全註解方式以實現自動建表
package hello.bean; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.command.BaseModel; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; @Table(name = "user") public class User extends BaseModel { private static final long serialVersionUID = 5199200306752426433L; @Column(name = "id", type = MySqlTypeConstant.INT, isAutoIncrement = true, length = 13, isKey = true) private int id; @Column(name = "name", type = MySqlTypeConstant.VARCHAR , length = 33, isNull = false) private String name; @Column(name = "age", type = MySqlTypeConstant.INT, length = 3, isNull = false) private int age; @Column(name = "money", type = MySqlTypeConstant.DOUBLE, isNull = false) private double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } }
UserDao.java
Dao 層開發基於全註解實現數據庫CRUD操做
package hello.dao; import hello.bean.User; import org.apache.ibatis.annotations.*; import java.util.List; /** * 基於註解實現數據庫 CRUD(create read update delete) */ @Mapper public interface UserDao { /** * 插入用戶信息 */ @Insert("INSERT INTO user(name, age, money) VALUES(#{name}, #{age}, #{money})") void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("money") Double money); /** * 經過名字查詢用戶信息 */ @Select("SELECT * FROM user WHERE name = #{name}") List<User> findUserByName(@Param("name") String name); /** * 查詢全部用戶信息 */ @Select("SELECT * FROM user") List<User> findAllUser(); /** * 根據 id 更新用戶信息 */ @Update("UPDATE user SET name = #{name},age = #{age},money= #{money} WHERE id = #{id}") void updateUser(@Param("name") String name, @Param("age") Integer age, @Param("money") Double money, @Param("id") int id); /** * 根據 id 刪除用戶信息 */ @Delete("DELETE from user WHERE name = #{name}") void deleteUser(@Param("name") String name); /** * 刪除user表裏面的全部數據 */ @Delete("DELETE from user WHERE 1 = 1") void deleteAllUserData(); }
UserController.java
Controller層實現http get的insert,query,update,delete,clear等操做。
package hello.controller; import hello.bean.User; import hello.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 實現 CRUD http 請求對應controller接口 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; // http://localhost:8333/user/insert?name=ace&age=18&money=0 @GetMapping("/insert") public List<User> insert(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "age", required = true) int age, @RequestParam(value = "money", required = true) double money) { userService.insertOneService(name, age, money); return userService.selectAllUser(); } // http://localhost:8333/user/query?name=ace @GetMapping("/query") public List<User> queryByName(@RequestParam(value = "name", required = false) String name) { if (name == null) { return userService.selectAllUser(); } return userService.selectUserByName(name); } @GetMapping("/update") public List<User> update(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "age", required = true) int age, @RequestParam(value = "money", required = true) double money) { userService.updateService(name, age, money); return userService.selectUserByName(name); } @GetMapping("/delete") public String delete(@RequestParam(value = "name", required = true) String name) { userService.deleteService(name); return "OK"; } @GetMapping("/clear") public List<User> testClear() { userService.clearService(); return userService.selectAllUser(); } @GetMapping("/changemoney") public List<User> testchangemoney() { userService.insertService(); userService.changemoney(); return userService.selectAllUser(); } }
UserService.java
Service層
package hello.service; import hello.bean.User; import hello.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.stream.Collectors; @Service public class UserService { @Autowired private UserDao userDao; /** * 根據名字查找用戶 */ public List<User> selectUserByName(String name) { return userDao.findUserByName(name); } /** * 查找全部用戶 */ public List<User> selectAllUser() { return userDao.findAllUser(); } /** * 插入兩個用戶 */ public void insertService() { userDao.insertUser("Ace", 22, 3000.0); userDao.insertUser("Blink", 19, 3000.0); } /** * 插入某個指定用戶 */ public void insertOneService(String name, int age, double money) { userDao.insertUser(name, age, money); } /** * 經過名字更新用戶信息 */ @Transactional public void updateService(String name, int age, double money) { List<User> users = userDao.findUserByName(name); if (users.isEmpty()) { return; } List<Integer> ids = users.stream().map(User::getId).collect(Collectors.toList()); ids.forEach(id -> userDao.updateUser(name, age, money, id)); } /** * 根據id 刪除用戶 */ public void deleteService(String name) { userDao.deleteUser(name); } /** * 清除表內全部數據 */ public void clearService() { userDao.deleteAllUserData(); } /** * 模擬事務。因爲加上了 @Transactional註解,若是轉帳中途出了意外 Ace 和 Blink 的錢都不會改變。 */ @Transactional public void changemoney() { userDao.updateUser("Ace", 22, 2000.0, 3); // 模擬轉帳過程當中可能遇到的意外情況 int temp = 1 / 0; userDao.updateUser("Blink", 19, 4000.0, 4); } }
MainApplication.java
Spring Boot啓動類,經過繼承CommandLineRunner在Spring Boot啓動的時候,在表自動建立完後會在表中插入一些數據。
package hello; import hello.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 這份demo須要本地安裝mySQL,並會在Spring Boot啓動的時候自動在sakila數據庫下按照sql.txt裏面的語句新建一個user的表 */ @SpringBootApplication public class MainApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Autowired UserService userService; @Override public void run(String... args) throws Exception { userService.insertService(); } }
功能演示:
(1)數據庫表自動建立,能夠經過console看到user表的建立
(2)查詢query
(3)insert插入數據
(4)update更新數據
(5)delete刪除數據
截止目前,一個基於Spring Boot 2.x,mySQL和myBatis完成簡單的用Web操做數據庫的全註解實現demo程序就已經完成啦~