문제

I have play-2.2.2 installed but I am having some trouble with some Ebean @OneToMany relationships when trying to access the ArrayList.

I basically have a User class which contains an ArrayList of an Address class. Code as follows:

@Entity
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE", discriminatorType = DiscriminatorType.STRING)
public class User extends Model{

    @Id
    private Long id;
    @OneToMany(cascade=CascadeType.ALL)
    private ArrayList<Address> addressList = new ArrayList<Address>();

    ...

    public void addAdress(Address address){
        this.addressList.add(address);
    }

And the class address

@Entity
public class Address extends Model {

    @Id
    private Long id;
    @ManyToOne
    private User user;

    ...

Now lets say I make a new user and a new address. I want to add the address to the new user's ArrayList and then save them. A bit like this:

User newUser = new User();
Address newAddress = new Address();
newUser.addAddress(newAddress);
newUser.save();

The problem with this code is that the address does not get saved. Shouldn't it be saved since I specified the CascadeType to all?

Another issue is that most of the time, my Users will be created before the address. So lets say I already a have a user. Now what I'm trying to do is to add a new address to that existing user:

User user = User.getCurrentUser();
user.addAddress(new Address());
user.save();

This code gives me an error, stating a NullPointerException in the method addAddress. It basically says that my addressList is null. Why is that? I just can't figure it out. Any help would be greatly appreciated.

도움이 되었습니까?

해결책

This should be simply because your JPA annotations are not correctly assigned.

You should tell ebean how to fetch address by adding the lookup info, otherwise it doesn't know how to do that:

@OneToMany(cascade=CascadeType.ALL, mappedBy = "id") // id is the field name in Address
private Set<Address> addressList;

also you should use Set as it's recommended: http://www.avaje.org/manydatatypes.html

The reason preferring set is not on top of my head but I recall lists could cause problems when you do multiple fetch joins.

and in your address class:

@ManyToOne
@JoinColumn(name = "(the id column name in user table)")
private User user;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top