0.先推薦一個工具——lombok,pom文件以下:java
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>compile</scope> </dependency>
可使用註解@Data 編譯時自動生成get,set方法,構造函數,toString方法。mysql
@Data @Entity public class Account { @Id private String id; private String account; @Column(name = "call_phone") private String phone; @Column(name = "nick_name") private String nickname; private String password; private String salt; private int userType; private String createUser; private Timestamp createTime; private int state; }
生成後的效果以下:spring
1.pom.xml文件下添加以下依賴,引入spring-boot-jpa的jar包,以及mysql驅動sql
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
2.在/src/main/resources/application.properties中配置spring datasource及hibernate方言數據庫
(Spring boot 默認使用hibernate做爲JPA的實現)tomcat
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.tomcat.max-active=100 spring.datasource.tomcat.max-idle=200 spring.datasource.tomcat.initialSize=20 spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
3.定義Entity和Repository(接口)。app
Entity--Account實體類以下:函數
@Entity會被spring掃描並加載,spring-boot
@Id註解在主鍵上工具
@Column name="call_phone" 指該字段對應的數據庫的字段名,若是相同就不須要定義。數據庫下劃線間隔和代碼中的駝峯法視爲相同,如數據庫字段create_time等價於Java類中的createTime,所以不須要用@Column註解。
@Data @Entity public class Account { @Id private String id; private String account; @Column(name = "call_phone") private String phone; @Column(name = "nick_name") private String nickname; private String password; private String salt; private int userType; private String createUser; private Timestamp createTime; private int state; }
Repository以下:
@Repository public interface AccountRepository extends JpaRepository<Account, String> { Account findOneByAccount(String account); }
4.在其餘@Component中調用
@RestController @RequestMapping("/subsystem") public class SubsystemAuthorityService { @Autowired AccountRepository accountRepository; @PostMapping(path = "/admin/info") public String getAdminInfo(String currentAccount) { Account account = accountRepository.findOneByAccount(currentAccount); System.out.println(account); return account.toString(); } }