获取最新的持久ID并将其返回

时间:2015-10-21 01:36:36

标签: java jpa

我正在使用JPA,我希望得到他新持久的id,但我不知道如何获得它。我能够获得id,但我没有显示它,但我不知道如何获得它的价值。

我有这种方法可以坚持:

    public Artist createArtist(int id, String name, int genre) {
        Artist artist = new Artist(id, name, genre);
        em.persist(artist);
        em.flush();

        System.out.println("Last ID: "+artist.getId()); 
        return artist;
    }

以及用于调用方法的几行代码:

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaBasicsTutorial");
        EntityManager em = emf.createEntityManager();
        ArtistService service = new ArtistService(em);
        Artist artista = new Artist();

        EntityTransaction transaction = em.getTransaction();
        transaction.begin();

        Artist artist = service.createArtist(artista.getId(),"Franz", 1); 
        System.out.println("Latest id: " +artista.getId()); // HOW TO GET ID HERE?

        transaction.commit();
        System.out.println(String.format("Persisted: %s\n", artist));

这是生成id的代码:

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    public Artist(int id, String name, int genre) {
        this.name = name;
        this.genre = genre;
    }

    public int getId() {
        return id;
    }

1 个答案:

答案 0 :(得分:1)

这里有2件物品 - 艺术家和艺术家。艺术家是坚持不懈的人。 artista对象没有持久化,因此您无法获得其ID。

您可能想要更改此行:

System.out.println("Latest id: " +artista.getId());

对此:

System.out.println("Latest id: " +artist.getId());

此外,在实例化Artist对象时,您无需分配其ID,因为根据您的映射,这是自动生成的。

因此,即使没有分配ID,也可以使用此代码。

Artist artist = new Artist();
artist.setName(name);
artist.setGenre(genre);
em.persist(artist);