Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

java - How to give Trigger generated value into Hibernate ValueObject?

In my Hibernate Application i'm using create a ValueObject class

@Entity
@Table(name="user")
public class UserVO{

    @Id
    @Column(name="S_ID")
    private String s_id;

    @Column(name="FIRSTNAME")
    private String firstName;

    @Column(name="LASTNAME")
    private String lastName;
 }

and in my Service class i'm writing like this

public void createOrUpdateUser(UserVO userVO) {
        userDAO.createOrUpdateUser(userVO);
    }

and in my DAO class i'm writing like this

private EntityManager entityManager;
public void createOrUpdateUser(UserVO userVO) throws DataAccessException {
        entityManager.persist(userVO);
    }

now i'm calling createOrUpdateUser(userVO) but it give error

Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()

Actually my data base i have created one trigger for user table to generate unique id for s_id column is their any problem for trigger..please suggest me..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using a trigger, the intended generation strategy is org.hibernate.id.SelectGenerator. However, in order to use this strategy, Hibernate must be able to locate the inserted row after insertion to see what value the trigger assigned there are 2 ways to do this.

First is to specifically configure the generator to tell it a column that define a unique key (at least logically) within the table:

@Id
@Column(name="S_ID")
@GeneratedValue( strategy = "trigger" )
@GenericGenerator( 
    name="trigger", strategy="org.hibernate.id.SelectGenerator",
    parameters = {
        @Parameter( name="keys", value="userName" )
    }
)
private String s_id;

private String userName;

The other is via Hibernate's natural-id support:

@Id
@Column(name="S_ID")
@GeneratedValue( strategy = "trigger" )
@GenericGenerator( name="trigger", strategy="org.hibernate.id.SelectGenerator" ) )
private String s_id;

@NaturalId
private String userName;

GenerationType.IDENTITY may work for you. It will really come down to the JDBC driver and how (if) it implements getGeneratedKeys


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...