Spring boot整合jpa
阿新 • • 發佈:2019-01-08
本文使用使用者、部門、角色的關係來演示整合過程
引入依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>
配置yml檔案和建立bean
本配置檔案只做簡單的示例,具體可以參考官方文件
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF8
username: root
password: root
jpa:
database: MYSQL
show-sql: true
hibernate:
ddl-auto: update
@Order(Ordered.HIGHEST_PRECEDENCE) @Configuration @EnableTransactionManagement(proxyTargetClass = true) @EnableJpaRepositories(basePackages = "com.example.dao") @EntityScan(basePackages = "com.example.entity") public class JpaConfiguration { @Bean PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() { return new PersistenceExceptionTranslationPostProcessor(); } }
建立實體類
/**
* 部門表
* Created by vip on 2018/10/24.
*/
@Entity
@Table(name = "deparment")
public class Deparment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
// get set
}
@Entity @Table(name = "role") public class Role implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; //get set }
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "create_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDate;
@ManyToOne
@JoinColumn(name = "did")
@JsonBackReference
private Deparment deparment;
@ManyToMany(cascade = {}, fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "roles_id")})
private List<Role> roles;
// get set
}
建立資料庫表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for deparment
-- ----------------------------
DROP TABLE IF EXISTS `deparment`;
CREATE TABLE `deparment` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`create_date` datetime DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`did` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKaakiarxhpooi8qqoe1twj0h5g` (`did`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`user_id` bigint(20) NOT NULL,
`roles_id` bigint(20) NOT NULL,
KEY `FKeog8p06nu33ihk13roqnrp1y6` (`roles_id`),
KEY `FK859n2jvi8ivhui0rl0esws6o` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
建立dao介面
@Repository
public interface DeparmentRepository extends JpaRepository<Deparment, Long> {
}
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
新增訪問方法
@RestController
@SpringBootApplication
public class DemoApplication {
private static Logger logger = LoggerFactory.getLogger(DemoApplication.class);
@Autowired
private UserRepository userRepository;
@Autowired
private DeparmentRepository deparmentRepository;
@Autowired
private RoleRepository roleRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/")
public String home() {
initDate();
findPage();
return "hello spring boot";
}
public void initDate() {
userRepository.deleteAll();
roleRepository.deleteAll();
deparmentRepository.deleteAll();
Deparment deparment = new Deparment();
deparment.setName("開發部");
deparmentRepository.save(deparment);
Assert.notNull(deparment.getId());
Role role = new Role();
role.setName("admin");
roleRepository.save(role);
Assert.notNull(role.getId());
User user = new User();
user.setName("user");
user.setCreateDate(new Date());
user.setDeparment(deparment);
List<Role> roles = roleRepository.findAll();
Assert.notNull(roles);
user.setRoles(roles);
userRepository.save(user);
Assert.notNull(user.getId());
}
public void findPage() {
Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "id"));
Page<User> page = userRepository.findAll(pageable);
Assert.notNull(page);
page.getContent().forEach(user -> {
logger.info("user name:{}, depa name:{}, role name:{}", user.getName(), user.getDeparment().getName(), user.getRoles().get(0).getName());
});
}
}