好像你的第一個問題可以分解成多個問題。
當我爲每個表創建控制器時,我使用CRUD方法來修改(或不)我的數據庫,並且爲HTML和VueJS部分返回一個視圖。但我的方法需要一個EntityManagerFactory,我應該在每個控制器類中創建一個字段,或者這不是我應該怎麼做?
由於您已經接受了建議使用spring-data-jpa
的答案。您將處理實體和存儲庫。
實體是將與您的數據庫交互的JPA託管bean。
@Entity
@Table(name = "rule")
public class Rule {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id;
String type;
...
@OneToOne
@JoinColumn(...)
Language language;
}
存儲庫將提供對數據庫執行操作所需的所有必要操作。使用JPA,您可以創建一個擴展CrudRepository的接口,它將爲您提供一些免費的CRUD操作。 findOne(/* id */)
,delete()
,save()
@Repository
public interface RuleRepository extends CrudRepository<Rule, Long> {
// You can easily specify custom finders
public List<Rule> findByType(String type);
}
但我的方法需要一個EntityManagerFactory的,我應該在每個控制器類中創建一個字段或這不是我應該怎麼辦?
它通常被抱怨有一個請求/響應對象是JPA實體。請參閱鏈接的答案should i use jpa entity in rest request and/or response
您可以採取多種方法來接收控制器請求並將響應發送到客戶端項目。
@Controller
public class RuleController {
@Autowired
private RuleRepository ruleRepository;
// Approach 1: Use Request Parameters - enforce inputs
@PostMapping("/rule/:id")
public Rule postWithRequestParams(@PathParam("id") Long id,
@RequestParam("type") String type,
@RequestParam("hint") String hint,
@RequestParam("languageField1") String languageField1) {
Rule inputRule = new Rule(id, type, hint, new Language(languageField1));
Rule responseRule = ruleRepository.save(inputRule);
return responseRule; // I would imagine you would want to set up a model for the response itself
}
// Approach 2: Use RequestBody - serialize Rule from the request
@PostMapping("/rule/:id")
public Rule postWithRequestParams(@PathParam("id") Long id, @RequestBody Rule inputRule) {
Rule responseRule = ruleRepository.save(inputRule);
return responseRule;
}
我需要創建一個bean文件,並配置它或persistence.xml中和pom.xml的是夠不夠?
如果已經添加spring-boot-starter-data-jpa
作爲依賴,很多bean配置中已經爲你做。
在你main/src/resources
(你應該有一個application.properties
或application.yml
)
spring.datasource.url= # JDBC url of the database.
spring.datasource.username= # Login user of the database.
spring.datasource.password= # Login password of the database.
春天做了很多的魔術和繁重的你。
你應該看看Spring Boot。你將不需要這些CRUD方法。 https://spring.io/guides/gs/accessing-data-jpa/ –
即使你不使用Spring Boot,也應該使用spring數據jpa。即使你不這樣做,你一定需要閱讀關於數據訪問和JPA集成的Spring文檔:https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access。 HTML。閱讀文檔是該工作的一部分。從長遠來看,它將爲您節省大量時間。 –