views:

41

answers:

2

Hi all,

I'm a newbie with JPA.

I need to map a search object to a table. The search object has only and id, name. The big object has more fileds id, name, adress and more.

I use this as big object view plaincopy to clipboardprint?

I use this as big object

@Entity
@Table(name="users")
public class User {

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

 private String name;
 private String adress;
 private String keywords;
}

//this is my search object
@XXX
public class UserSearch {

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

 private String name;

}

What annotations I need to use to map the search object to the table users?

I'm using spring+struts2+hibernate+JPA.

Help is appreciated! Thanks!

A: 

Just like that? It should work. Did you try it and get an error? Telling us what the error is may help. It's probably also wise to make the partial view immutable if possible. If you explain why you want to do this, there may be alternatives :)

@Entity
@org.hibernate.annotations.Entity(mutable=false)
@Table(name="users")
public class UserSearch implements Serializable {}

Should work just fine.

Affe
+1  A: 

What annotations I need to use to map the search object to the table users?

You need to use the @Table annotation if you want to map it to a table that doesn't default to the entity name:

@Entity
@Table(name = "Users")
public class UserSearch {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

}

But if this class is used for search results and if you don't plan to persist UserSearch instances, you don't really need to make it an entity. Assuming you provide the appropriate constructor:

public class UserSearch {
    private long id;
    private String name;

    public UserSearch(long id, String name) {
        this.id = id;
        this.name = name;
    }
}

You could use this class in conjunction with a SELECT NEW, like this:

SELECT NEW com.acme.UserSearch(u.id, u.name) FROM User u
Pascal Thivent