[英]Insert data to two tables in the same time. h2 database
我在編寫 SQL 查詢時遇到問題。 我想將數據插入我的 h2 數據庫。 我的應用程序使用 spring 引導和 memory h2 數據庫。
我的兩個實體:
@Entity
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@OneToMany(cascade = CascadeType.ALL)
private List<ScreeningTime> screeningTime;
private int screeningRoomId;
}
@Entity
public class ScreeningTime {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long screeningTime;
}
我想使用 SQL 查詢插入數據:
INSERT INTO PUBLIC.MOVIES (TITLE, SCREENING_TIME, SCREENING_ROOM_ID)
VALUES ('Film1', 1573399800000, 1);
我的查詢是錯誤的,但我不知道如何解決它。 你可以幫幫我嗎?
只需使用 spring 數據 jpa
在您的項目中創建存儲庫。 幫助https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference
ScreeningTime time1=new ScreeningTime ();
time1.setScreeningTime("yourtime");
ScreeningTime time2=new ScreeningTime ();
time2.setScreeningTime("yourtime");
List<ScreeningTime> times=new ArrayList<>();
times.add(time1);
times.add(time2);
Movie m=new Movie();
m.setTitle("Film1");
m.setScreeningRoomId(1);
m.setScreeningTime(times);
repository.save(m);
添加屏幕時間。 你可以看電影
@Repository
public interface ScreeningTime extends CrudRepository<ScreeningTime , Long> {
@Modifying
@Query(value = "insert into ScreeningTime (id,screeningTime) VALUES (:id,:screeningTime)", nativeQuery = true)
@Transactional
void saveScreen(@Param("id") String id, @Param("screeningTime") Long screeningTime);
}
如果您使用 Spring 啟動,那么您也可以在您的服務 class 中自動裝配 EntityManager 並使用持久方法來保存您的更改。 請確保將您的服務標記為 class 方法@Transactional。 另外,確保在 pom.xml 文件中添加 spring-data-jpa。
@Autowired EntityManager em;
// 在此處添加您的代碼以填充電影 object
em.persist(電影);
希望這可以幫助!!
我想將 movieId 字段添加到 ScreeningTime 實體。 您的示例或實體屬性應該改變什么? 我應該添加一些注解嗎? 還是屬性?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.