开发者

How to map a search object to a class with more fields with JPA annotations

开发者 https://www.devze.com 2023-01-01 04:42 出处:网络
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'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!


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


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.

0

精彩评论

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