增删改查很爽就对了 适合业务性比较单一的项目
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- springboot,jpa 整合包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql 驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在 application.properties 中添加:
# 数据库连接配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=tiger
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
在 MySQL 中创建名为 springboot 的数据库,在该库中创建 role 表: 注意,主键 ID 为 AUTO_INCREMENT 自增。
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
;
添加相应的注解 getset
@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;
}
public interface RoleRepository extends JpaRepository<Role, Integer>{
}
@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);
}
}