上一篇 <<<SpringBoot全局异常捕获
下一篇 >>>SpringBoot整合Mybatis分页插件
通用配置
a.添加数据库驱动依赖
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
b.在maven工程的main/java/resources目录下名为“application.yml”的配置文件中配置数据库信息
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
1.整合jdbctemplate
注意: spring-boot-starter-parent要在1.5以上,添加相关的依赖及代码演示
<!-- jdbcTemplate 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void createUser(String name, Integer age) {
jdbcTemplate.update("insert into users values(null,?,?);", name, age);
}
}
2.整合mybatis
添加相关依赖及代码演示
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
public interface UserMapper {
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
##启动类上要加@MapperScan,或者在每个Mapper上加@Mapper注解才会生效
@MapperScan("com.jarye.mapper")
@SpringBootApplication
public class MybatisApp {
public static void main(String[] args) {
SpringApplication.run(MybatisApp.class, args);
}
}
3.整合JPA
添加相关依赖及代码演示
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
@Entity(name = "users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
}
public interface UserDao extends JpaRepository<User, Integer> {
}
@RestController
public class IndexController {
@Autowired
private UserDao userDao;
@RequestMapping("/jpaFindUser")
public Object jpaIndex(User user) {
Optional<User> userOptional = userDao.findById(user.getId());
User reusltUser = userOptional.get();
return reusltUser == null ? "没有查询到数据" : reusltUser;
}
}
推荐阅读:
<<<SpringBoot核心设计理念和核心组件
<<<SpringBoot中有哪些starter
<<<如何自定义SpringBoot starter
<<<SpringBoot启动流程说明
<<<SpringBoot常用注解及外部jar包注入方式
<<<SpringBoot之web开发
<<<SpringBoot全局异常捕获
<<<SpringBoot整合Mybatis分页插件
<<<SpringBoot使用Atomikos技术整合多数据源
<<<SpringBoot实现热部署
<<<SpringBoot性能调优
<<<SpringBoot的Actuator监控和Admin-UI可视化
<<<SpringBoot常见面试问题
网友评论