1.JdbcTemplate
Spring Boot默认支持JdbcTemplate(无需配置),仅需要使用@Autowired注解注入即可使用。
@Autowired
private JdbcTemplate jdbcTemplate;
但实际工作开发中,直接使用JdbcTemplate的并不多。
2.Spring Data JPA
现在的开发工作中,借助开发框架,我们已经不用编写原始的访问数据库的代码,也不用调用JDBC或者连接池等诸如此类的被称作底层的代码,我们将使用“高级”的方式访问数据库。目前数据库访问主要有Hibernate和Mybatis两大主流ORM框架。然后Spring Boot使用JPA将Hibernate的思想发挥到极致,我们可以实现0配置(极少配置)完成数据库的操作。
2.1 添加依赖
compile('org.mariadb.jdbc:mariadb-java-client:2.2.3')
compile('org.springframework.boot:spring-boot-starter-data-jpa:2.0.0.RELEASE')
2.2 在application.properties中添加datasource及jpa相关配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
# create:每次加载hibernate时根据model类生成表,无论表及表中数据是否存在
# create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除
# update:表不存在时,根据model生成表;表存在时,根据model更新表结构
# validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值
spring.jpa.properties.hibernate.hbm2ddl.auto=update
2.3 定义实体User.java
package com.example.springboot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@SuppressWarnings("unused")
@Entity
public class User {
@Id
private Long id;
@Column
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.4 继承JpaRepository
package com.example.springboot.repository;
import com.example.springboot.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@SuppressWarnings("unused")
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("from user u where u.name=:name")
User findUser(@Param("name") String name);
}
2.5 创建测试类,可以查到数据库中的数据
package com.example.springboot;
import com.alibaba.fastjson.JSONObject;
import com.example.springboot.model.User;
import com.example.springboot.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRepository {
@Autowired
private UserRepository userRepository;
@Test
public void queryUser() throws Exception {
User user = userRepository.findUser("小明");
System.out.println(JSONObject.toJSONString(user));
}
}
2.6 实际上JpaRepository本身已经提供了findAll()
、save()
、deleteInBatch()
、getOne()
等方法,我们甚至只要继承它而不需要其它任何操作就能实现数据库的操作。
以下代码使用findAll()
及分页查实现了一个简单的轮询发送邮件逻辑。
EmailRepository.kt
@Repository
interface EmailRepository: JpaRepository<Email, Long>
EmailService.kt
interface EmailService {
/**
* 创建Email
*/
fun createEmail(email: Email): Boolean
/**
* 发送Email
*/
fun sendEmail(status: Int = 0)
}
EmailServiceImpl.kt
@Service
class EmailServiceImpl : EmailService {
private val logger = LoggerFactory.getLogger(this.javaClass)
@Autowired
private lateinit var emailRepository: EmailRepository
@Autowired
private lateinit var mailHelper: MailHelper
override fun createEmail(email: Email): Boolean {
val s = emailRepository.save(email)
println(s.toString())
return true
}
@Transactional
override fun sendEmail(status: Int) {
// 每次处理5条邮件记录
val pageRequest = PageRequest.of(0, 5, Sort.Direction.ASC, "createTime")
val email = Email(status = status)
val exampleMatcher = ExampleMatcher.matching().withMatcher("status", ExampleMatcher.GenericPropertyMatchers.exact())
val example: Example<Email> = Example.of(email, exampleMatcher)
val page: Page<Email> = emailRepository.findAll(example, pageRequest)
page.content.forEach { it ->
// 遍历操作,发送邮件
}
}
}
3.Mybatis
3.1 其它配置跟前面相同,添加依赖
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1')
3.2 创建Mapper
package com.example.springboot.mapper;
import com.example.springboot.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Mapper
@SuppressWarnings("unused")
@Repository
public interface UserMapper {
@Select("select * from user where name = #{name}")
User findByName(@Param("name") String name);
}
3.3 创建测试类
package com.example.springboot;
import com.alibaba.fastjson.JSONObject;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestMapper {
@Autowired
private UserMapper userMapper;
@Test
public void query() throws Exception {
User user = userMapper.findByName("小明");
System.out.println(JSONObject.toJSONString(user));
}
}
3.4 其它配置不变,就能以Mybatis的方式操作数据库了,也是比较简单。
网友评论