Spring Boot 2.x 整合 Mybatis 3.x

步驟1:加入依賴(starter 依賴,對應數據庫的驅動包依賴,第三方數據源依賴)html

<!-- 引入starter-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
    <scope>runtime</scope>    
</dependency>

<!-- MySQL的JDBC驅動包 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> -->   

<!-- Oracle的JDBC驅動包,注意:Oracle驅動包沒法在maven公共倉庫下載,這裏的依賴是本人nexus私服上的地址 --> 
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.1.0</version>
</dependency>

<!-- 引入第三方數據源 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> -->

注意:java

1)數據源能夠使用 Spring Boot 自帶的數據源,能夠不用第三方數據源mysql

2)Oracle 驅動包沒法在 maven 公共倉庫下載,這裏的依賴是本人發佈在 nexus 私服上的依賴,請不要照搬git

mybatis-spring-boot-starter 對應的 maven 倉庫地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-startergithub

步驟2:配置文件中設置數據源信息spring

#能夠自動識別,因此能夠不用指定 #spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl spring.datasource.username=developer spring.datasource.password=developer #若是不使用第三方數據源,則 Spring Boot 使用默認的數據源:com.zaxxer.hikari.HikariDataSource #spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

加載配置,注入 SqlSessionFactory 等都是 Spring Boot 幫咱們完成。sql

步驟3:開發 mapper數據庫

public interface UserMapper {   //推薦使用#{}取值,不要用${},由於存在注入的風險
  @Insert("INSERT INTO user_info(id,name,phone,create_time,age) VALUES(#{id},#{name}, #{phone}, #{createTime},#{age})")   //@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java對象的屬性;keyColumn表示數據庫的字段
  int insert(User user); }

注意:oracle數據庫不提供自增主鍵,因此必須手動插入主鍵apache

User 類api

public class User { private int id; private String name; private String phone; private int age; //省略getter、setter方法
}

建表SQL

create table user_info( id INTEGER    primary key, name varchar2(20), phone varchar2(16), create_time DATE, age INTEGER )

步驟4:啓動類增長 mapper 掃描

@SpringBootApplication @MapperScan("com.jwen.base_project.mapper") public class BaseProjectApplication { public static void main(String[] args) { SpringApplication.run(BaseProjectApplication.class, args); } }

項目目錄結構以下

步驟5:進行測試

@Service public class UserServiceImpl implements UserService{   @Autowired   private UserMapper userMapper; @Override public int add(User user) {     userMapper.insert(user);     int id = user.getId();     return id; } }

Controller

@RestController @RequestMapping("/api/v1/user") public class UserController {   @Autowired   private UserService userService;   @GetMapping("add")   public Object add(){     User user = new User();     user.setId(2);     user.setAge(22);     user.setCreateTime(new Date());     user.setName("張三");     user.setPhone("10010000");     int id = userService.add(user); return JsonData.buildSuccess(id);   } }

瀏覽器地址欄輸入:http://localhost:8080/api/v1/user/add

數據庫的結果

 

其他的如:查詢、刪除、修改也是同樣的操做

@Select("SELECT * FROM user") @Results({   @Result(column = "create_time",property = "createTime") //javaType = java.util.Date.class }) List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}") @Results({   @Result(column = "create_time",property = "createTime") }) User findById(Long id); @Update("UPDATE user SET name=#{name} WHERE id =#{id}") void update(User user); @Delete("DELETE FROM user WHERE id =#{userId}") void delete(Long userId);

若是想在控制檯打印sql語句,能夠在配置文件中添加如下配置

#增長打印sql語句,通常用於本地開發測試 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 若是想要引入事務,能夠在方法上添加註解@Transactional,以下代碼所示,發生異常時,事務回滾。

@Override @Transactional(propagation=Propagation.REQUIRED) public int addAccount() {   User user = new User();   user.setID(4);   user.setAge(9);   user.setCreateTime(new Date());   user.setName("事務測試");   user.setPhone("000121212");   userMapper.insert(user);   int a = 1/0;   return user.getId(); }

 


Mybatis參考資料:

http://www.mybatis.org/mybatis-3/zh/java-api.html

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples

整合問題集合:

https://my.oschina.net/hxflar1314520/blog/1800035

https://blog.csdn.net/tingxuetage/article/details/80179772

相關文章
相關標籤/搜索