整合 Swagger2
添加依赖
io.springfox
springfox-swagger2
2.7.0
io.springfox
springfox-swagger-ui
2.7.0
重新创建一个配置类,如下:
[图片上传中...(image-397907-1524637363711-1)]
为了能更好的说明接口信息,我们还可以在 Controller 类上使用 Swagger2 相关注解说明信息。
我们以 FastJsonController 为例:
@Api(value = "FastJson测试", tags = { "测试接口" })
@RestController
@RequestMapping("fastjson")
public class FastJsonController {
@ApiOperation("获取用户信息")
@ApiImplicitParam(name = "name", value = "用户名", dataType = "string", paramType = "query")
@GetMapping("/test/{name}")
public User test(@PathVariable("name") String name) {
User user = new User();
user.setId(1);
user.setUsername(name);
user.setPassword("jack123");
user.setBirthday(new Date());
return user;
}
}
注意,上边的方法是用 @GetMapping 注解,如果只是使用 @RequestMapping 注解,不配置 method 属性,那么 API 文档会生成 7 种请求方式。
启动项目,打开浏览器访问 http://localhost:8080/swagger-ui.html。结果如下图:
[图片上传中...(image-ad4754-1524637363711-0)]
持久层配置
整合 JdbcTemplate
添加依赖
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
配置数据库连接
在 application-dev.properties 中添加:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
其中,可以不指定 driver-class-name,因为 spring boot 会自动识别 url。
测试
在 MySQL 中创建名为 springboot 的数据库,在该库中创建 user 表:
CREATE TABLE user
(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(64) NOT NULL,
`birthday` DATE NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3
;
建实体类
public class User implements Serializable{
private static final long serialVersionUID = -6249397911566315813L;
private Integer id;
private String username;
private String password;
private Date birthday;
}
setter 和 getter 方法此处省略。
dao 接口
接口和实现类如下:
public interface UserDao {
public int insert(User user);
public int deleteById(Integer id);
public int update(User user);
public User getById(Integer id);
}
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int insert(User user) {
String sql = "insert into user(id,username,password,birthday) values(?,?,?,?)";
return this.jdbcTemplate.update(
sql,
user.getId(),
user.getUsername(),
user.getPassword(),
user.getBirthday()
);
}
@Override
public int deleteById(Integer id) {
String sql = "delete from user where id = ?";
return this.jdbcTemplate.update(sql,id);
}
@Override
public int update(User user) {
String sql = "update user set password = ? where id = ?";
return this.jdbcTemplate.update(
sql,
user.getPassword(),
user.getId()
);
}
@Override
public User getById(Integer id) {
String sql = "select * from user where id = ?";
return this.jdbcTemplate.queryForObject(sql, new RowMapper() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setBirthday(rs.getDate("birthday"));
return user;
}
},id);
}
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {
@Autowired
private UserDao userDao;
@Test
public void testInsert() {
User user = new User();
user.setId(1);
user.setUsername("张三");
user.setPassword("zhangsan");
user.setBirthday(new Date());
int result = this.userDao.insert(user);
System.out.println(result);
}
@Test
public void testGetById() {
User user = this.userDao.getById(1);
System.out.println(user.getUsername());
}
@Test
public void testUpdate() {
User user = new User();
user.setId(1);
user.setPassword("zhangsan123");
this.userDao.update(user);
}
@Test
public void testDeleteById() {
int result = this.userDao.deleteById(1);
System.out.println(result);
}
}
测试结果省略...
如需打印日志,在日志配置文件中添加如下配置:
整合 Spring-data-jpa
添加依赖
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
配置数据库连接
jdbc
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
建表
CREATE TABLE role
(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(10) NOT NULL,
`descr` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
注意,主键 ID 为 AUTO_INCREMENT 自增。
建实体类
添加相应的注解
@Entity
public class Role implements Serializable{
private static final long serialVersionUID = 3926276668667517847L;
@Id
@GeneratedValue
private Integer id;
@Column
private String name;
@Column
private String descr;
}
setter 和 getter 方法此处省略。
Repository 接口
public interface RoleRepository extends JpaRepository
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class RoleRepositoryTest {
@Autowired
private RoleRepository roleRepository;
@Test
public void testInsert() {
Role role = new Role();
role.setName("管理员");
role.setDescr("测试");
Role result = this.roleRepository.save(role);
System.out.println(result);
}
@Test
public void testFindOne() {
Role role = this.roleRepository.findOne(1);
System.out.println(role);
}
@Test
public void testUpdate() {
Role role = new Role();
role.setId(1);
role.setName("管理员");
role.setDescr("控制权限");
Role result = this.roleRepository.save(role);
System.out.println(result);
}
@Test
public void testDelete() {
this.roleRepository.delete(1);
}
}
测试结果省略...
整合 Mybatis
整合 MyBatis 有两种方式:
使用 mybatis 官方提供的 Spring Boot 整合包实现。
使用 mybatis-spring 整合的方式,也就是传统的方式(推荐,此方式容易控制 MyBatis的配置)。
配置依赖
方式一:
添加依赖:
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0
mysql
mysql-connector-java
配置数据库连接:
在 application.properties 中添加:
数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3380/springboot?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=tiger
mybatis 配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
方式二:
添加依赖:
org.mybatis
mybatis
3.4.4
org.mybatis
mybatis-spring
1.3.1
创建配置类:
@Configuration
public class MyBatisConfiguration {
@Bean
@ConditionalOnMissingBean // 当容器里没有指定的 Bean 的情况下创建该对象
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 设置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
// 设置mybatis的主配置文件
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");
sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
// 设置mapper映射文件
Resource[] mapperXml;
try {
mapperXml = resolver.getResources("classpath:mybatis/mapper/*.xml");
sqlSessionFactoryBean.setMapperLocations(mapperXml);
} catch (IOException e) {
e.printStackTrace();
}
// 设置别名包
//sqlSessionFactoryBean.setTypeAliasesPackage("com.guige");
return sqlSessionFactoryBean;
}
@Bean
@ConditionalOnBean(SqlSessionFactoryBean.class) // 当 SqlSessionFactoryBean 实例存在时创建对象
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.guige.springbootdemo.mapper");
return mapperScannerConfigurer;
}
}
此方式也需要在 applicaton.properties 配置数据库连接,当不需要在文件中配置 mybatis 相关参数。
以上便是两种方式的配置的不同之处。
在 src/main/resources 下创建 mybatis 文件夹,并在 mybatis 文件夹中创建 "mybatis-config.xml" 配置文件,内容如下:
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
mybatis 文件夹下再创建一个 "mapper" 文件夹,里边存放 Mpper 接口对应的 mapper 映射文件。
测试
建表
在 MySQL 中创建名为 springboot 的数据库,在该库中创建 department表:
CREATE TABLE department
(
`id` INT(11) NOT NULL,
`name` VARCHAR(10) NOT NULL,
`descr` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
;
实体类
public class Department implements Serializable{
private static final long serialVersionUID = 6067283535977178571L;
private Integer id;
private String name;
private String descr;
}
setet 和 getter 方法省略。
Mapper 接口
@Mapper
public interface DepartmentMapper {
public void insert(Department department);
public Department getById(Integer id);
public void update(Department department);
public void deleteById(Integer id);
}
mybatis/mapper/departmentMapper.xml :
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
insert into department(id,name,descr) values(#{id},#{name},#{descr})
update department set descr = #{descr} where id = #{id}
delete from department where id = #{id}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class DepartmentMapperTest {
@Autowired
private DepartmentMapper departmentMapper;
@Test
public void testInsert() {
Department department = new Department();
department.setId(1);
department.setName("研发部");
department.setDescr("开发产品");
this.departmentMapper.insert(department);
}
@Test
public void testGetById() {
Department department = this.departmentMapper.getById(1);
System.out.println(department);
}
@Test
public void testUpdate() {
Department department = new Department();
department.setId(1);
department.setDescr("开发高级产品");
this.departmentMapper.update(department);
}
@Test
public void testDeleteById() {
this.departmentMapper.deleteById(1);
}
}
Mybatis生成代码
在pom中build的插件中添加生成插件
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
src/main/resources/generator/generatorConfig.xml
true
true
在resources下创建 generator文件夹
配置config.properties
datasource.url=jdbc:oracle:thin:@dbServer254:1521:guigedb1
datasource.username=mis
datasource.password=mis
datasource.driverClassName=oracle.jdbc.OracleDriver
项目目录下执行命令:mvn mybatis-generator:generate
targetJavaProject=src/main/java
targetMapperBasePackage=com.guige.springbootdemo
targetModelPackage=com.guige.springbootdemo.entity
targetMapperPackage=com.guige.springbootdemo.mapper
targetResourcesProject=src/main/resources
targetXMLPackage=mybatis/mapper
创建generatorConfig.xml 配置文件
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">