Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4252582
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T04:48:52+00:00 2026-05-21T04:48:52+00:00

How to add the first entity of recursive non-null relation? The trouble occurs when

  • 0

How to add the first entity of recursive non-null relation?

The trouble occurs when trying to use my default audit guard (EntityListener) for user entities. Hibernate isnt able to insert first user. The example is simplification of situation:

@Entity
class User {
    @Id @GeneratedValue
    private Long id;
    @Basic
    private String name;
    @ManyToOne(optional=false)
    @JoinColumn(nullable=false,updatable=false)
    private User createdBy;

    // getters & setters
    // equals & hashcode are based on name
}

And I have tried something like:

User user = new User();
user.setName( "Some one" );
user.setCreatedBy( user );

Hibernate fails and root exception is:

 com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into 
column 'createdby_id', table 'mydb.user'; column does not allow nulls. INSERT fails.

I know several workarounds: insert first entity manually (SQL insert) or set nullable=true. First is just annoying and second is fail point of integrity (custom audit listener & db trigger required). Is there better options? Or, in the other words: is there JPA-only solution?

My platform is: SQL Server 2008 and Hibernate 3.6 as JPA2 provider.

Edit: At first, I was using persist(). I tried merge() which could make more intelligent guess but no difference. And I tried CascadeType.MERGE too.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T04:48:53+00:00Added an answer on May 21, 2026 at 4:48 am

    The not null constraint mandates that you insert the user.id in the reference field, but if you have set the id field to be autogenerated, that value is not known until after the insert. To solve this, you could use a sequence to generate the @Id

    create sequence SEQ_USER
    

    and insert the first user by fetching the next value of that sequence, and setting both fields to that value. With a native SQL query from JPA this looks like:

    User u = new User();
    u.setName("First User");
    Query q = em.createNativeQuery("VALUES nextval for SEQ_USER");
    Long nextId = Long.valueOf((Integer) q.getSingleResult());
    q = em.createNativeQuery("insert into user (id, name, created_by) values (?, ?, ?)");
    q.setParameter(1, nextId).setParameter(2, u.getName()).setParameter(3, nextId);
    q.executeUpdate();
    // don't forget to bring u into persistence context
    u = em.find(User.class, nextId);
    

    which is a little kludgy but has to be called only once. All other users would be persisted the normal way (using SEQ_USER as Generator sequence for the @Id)

    Alternatively, you could write your own SequenceGenerator do just that:

    public class UserIdGenerator implements IdentifierGenerator {
    
      @Override
      public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
    
        User o = (User) object;
        Connection connection = session.connection();
        try {
          PreparedStatement ps = connection.prepareStatement("VALUES nextval for SEQ_USER");
          ResultSet rs = ps.executeQuery();
          if (rs.next()) {
            return rs.getLong(1);
          }
        } catch (SQLException e) {
          log.error("Unable to generate Id: " + e.getMessage(), e);
        }
        return null;
      }
    }
    

    In User, you qould set that generator as:

    @Id
    @GenericGenerator(name = "idSource", strategy = "com.example.db.UserIdGenerator", parameters = { @Parameter(name = "sequence", value = "SEQ_USER") })
    @GeneratedValue(generator = "idSource")
    private Long id;
    

    and then

    User u = new User();
    u.setName("First User");
    u.setCreatedBy(u);
    em.persist(u);
    

    works as expected.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to add a space before every capital letter, except the first one.
I am attempting to add Entity Framework, code first, to an MVC application that's
How can I add an Image type to an EF4 Code First Entity? I
I am using Entity framework Code First CTP5 and I am trying to find
I'm using Entity Framework for the first time, and I need to add business
The goal: I'm trying to use the new Entity Framework 4.1 DbContext API (using
I just tried (for the first time, I might add) a port upgrade installed
Every time you start Visual Studio, the first time you click Add Reference to
I was trying to add a favicon to a website earlier and looked for
What Firefox add-ons do you use that are useful for programmers?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.