如果我有一个包含另一个类的对象的实体,例如其中包含a的Book
实体Publisher
如下关联实体:
@ManyToOne @JoinColumn(name="PUB_CODE", referencedColumnName = "PUB_CODE") private Publisher pub;
这是一个安全/正确(我在这个例子中看到DB中的正确数据,但不是100%确定它是否适用于所有情况)方法在数据库中发布具有外键关联的对象?我不知道在事务原子性或线程方面是否安全,或者它是否有效.相关代码如下:
Book.java
package app.domain; /*imports*/ @Entity public class Book implements Serializable{ /** * */ private static final long serialVersionUID = -6902184723423514234L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false, unique=true) private String bookName; @Column(nullable = false) private int pageCount; @ManyToOne @JoinColumn(name="PUB_CODE", referencedColumnName="PUB_CODE") private Publisher pub; /*public getters and setters*/ }
Publisher.java
package app.domain; /*imports*/ @Entity public class Publisher implements Serializable { private static final long serialVersionUID = 4750079787174869458L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name="PUB_CODE",nullable = false, unique = true) private String publisherCode; @Column(nullable = false) private String publisherName; /*public getters and setters*/ }
BookRepo.java
package app.service; /*imports*/ public interface BookRepo extends JpaRepository{ @Query("SELECT pb FROM Publisher pb WHERE pb.publisherCode = TRIM(UPPER(:pubCode))") public Publisher findPublisherByPubCode(@Param("pubCode")String pubCode); }
BookController.java
package app.controller; /*imports*/ @RestController @RequestMapping(value = "/books") public class BookController { private BookRepo bookRepo; @Autowired public BookController(BookRepo bookRepo) { this.bookRepo = bookRepo; } //The ApiPathParam is for JSONDOC purposes @RequestMapping(value = "/create", method = RequestMethod.POST) public Listcreate(@ApiPathParam(name = "book") @RequestBody Book book, @ApiPathParam(name = "pubCode") @RequestParam("pubCode") String pubCode) { // Assume exception handling Publisher pbToAttachToThisBook = bookRepo.findPublisherByPubCode(pubCode); book.setPub(pbToAttachToThisBook); bookRepo.save(book); return bookRepo.findAll(); } }
发布对象主体(输入到POST工具):
{ "bookName": "goosebumps", "id": 0, "pageCount": 332, "pub": { "id": 0, "publisherCode": "", "publisherName": "", "serialVersionUID": 0 }, "serialVersionUID": 0 }
提供的pubCode参数输入,也在POST工具中,与上面相同的调用:'SC'
执行上面的代码之后,在Book表中,上面的书中有一个条目,PUB_CODE
其外键列已填入'SC'
,并且List
被调用的POST控制器方法的返回显示新添加的书包含Publisher
实体发布者的信息(例如全名"Scholastic")PUB_CODE='SC'
已存在于数据库中.
谢谢.