好像你的第一个问题可以分解成多个问题。
当我为每个表创建控制器时,我使用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。阅读文档是该工作的一部分。从长远来看,它将为您节省大量时间。 –