开发者

Issue with a List<Long> using PlayFramework and JPA

开发者 https://www.devze.com 2023-03-19 03:05 出处:网络
I am working on a project using the Play!Framework, and I an encoutering some issues with JPA. It seems that it doesn\'t save my List, or doesn\'t manage to retrieve it from the DB.

I am working on a project using the Play!Framework, and I an encoutering some issues with JPA. It seems that it doesn't save my List, or doesn't manage to retrieve it from the DB.

Here is my User class :

@Entity
public class User extends Model {
    public String login;
    public String password;
    public String name;
    public String email;
    @ElementCollection
    public List<Long> eventStreamIds;
    @Transient
    UserEventBuffer eventBuffer;

    public User(String login, String password, String name, Strin开发者_Python百科g email, ArrayList<Long> eventStreamIds) {
        this.login = login;
        this.password = password;
        this.name = name;
        this.email = email;
        this.eventStreamIds = eventStreamIds;
            UserEventBuffer eventBuffer = new UserEventBuffer();
        }
}

I have another class, a ModelManager, which constructor is as following :

public ModelManager() {
    User u = new User("user1", "pwd", "Alex", "test@test.com");
    EventStreamMC eb = new EventStreamMC("http://www.wservice.com/stream1");
    streams.add(eb);
    u.eventStreamIds.add(eb.id);
    Logger.info("before : " + u.eventStreamIds.size());
    u.save();
    User u2 = User.find("byLoginAndPassword", "user1", "pwd").first();
    Logger.info("after : " + u2.eventStreamIds.size());
}

(My EventStreamMC also extends Model and has an @Entity tag, so its Long id is automatically generated) When i run this code, here is the result :

before = 1
after = 0

So the List is empty after the call to the find() method.

How can I make it work ?


ID are generated only on save and eb is never saved in your code. ed.id will be empty when you add it to your list.

EDIT :

I'll go a little further in my explanations.

The first logger is returning 1 since it is a Java List Object. It is a plain list, you add an element and the size increases. No surprises, here. Plain java. And absolutly nothing to do with Play!.

Second logger is not displaying anything since ID are generated on commit precisly. And since, you are still in the same transaction, no save is performed until the very end of the execution. If you really want this to work in the same http request/transaction, use this :

Model.em().getTransaction().commit();

For more information, check out official Play documentation on Transactions.

0

精彩评论

暂无评论...
验证码 换一张
取 消