-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Cannot add or update a child row
PostPosted: Tue Mar 16, 2010 1:20 pm 
Newbie

Joined: Tue Mar 16, 2010 1:13 pm
Posts: 1
Hi all.

I have the following code:

Code:
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = { "username" }))
public class User extends BaseEntity {
    @Column(name = "username", length = 50, nullable = false)
    private String username;

    @Column(name = "password", length = 50, nullable = false)
    private String password;

    @Column(name = "enabled", columnDefinition = "TINYINT")
    private boolean enabled;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Authority> authorities;


Code:
@Entity
@Table(name = "authorities", uniqueConstraints = @UniqueConstraint(columnNames= {"username", "authority"}))
public class Authority extends BaseEntity {
   
    @ManyToOne(optional = false)
    @JoinColumn(name = "username", referencedColumnName = "username", updatable = true)
    private User user;

    @Column(name = "authority", length = 50, nullable = false)
    private String authority;


and

Code:
   public static void main(String[] args) {
       
       EntityManagerFactory emf = new HibernateUtils().getEMF();
        EntityManager entityManager = (EntityManager) emf.createEntityManager();
        entityManager.getTransaction().begin();
       
        User u = new User();
        u.setUsername("asd");
        u.setPassword("asd");
       
       
        save(u, entityManager);
       
        User u1 = entityManager.find(User.class, 1l);
        u1.setUsername("asda");
       
        save(u1, entityManager);
       
        HibernateUtils.commit(entityManager);
       
    }

    private static void save(User entity, EntityManager entityManager) {
        Set<Authority> authorities = entity.getAuthorities();
        System.out.println(authorities);
        if (null != authorities) {
            entity.setAuthorities(null);
            for (Authority authority : authorities) {
                entityManager.remove(authority);
            }           
        }
       
        Authority auth = new Authority();
        auth.setUser(entity);
        boolean isAdmin = true;
        auth.setAuthority(isAdmin ? "ROLE_ADMIN" : "ROLE_USER");
        entity.addAuthority(auth);
       
        entity.setEnabled(true);       

        if (entity.isNew()) {
            entityManager.persist(entity);
        } else {
            entityManager.merge(entity);
        }
    }


After execution :
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`test`.`authorities`, CONSTRAINT `FK2B0F1321148B353B` FOREIGN KEY (`username`) REFERENCES `users` (`username`))
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1169)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:693)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1303)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:72)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
... 31 more

Any ideas why? And how to avoid it?

Thanks for the help.


Top
 Profile  
 
 Post subject: Re: Cannot add or update a child row
PostPosted: Wed Mar 17, 2010 6:21 am 
Expert
Expert

Joined: Tue Jun 16, 2009 3:36 am
Posts: 990
Hi,

you refer business key User.username as foreign key instead to refer to users primary key
(the information how Users primary key (id) is named is missing in this thread).
Generally foreign keys should always point to the primary key of foreign table,
because only primary keys are guaranteed to be immutable.
If you indeed absolutely want to refer a naturalId (aka business key) as foreign key,
then you must never change the value of such naturalId.
Changing the username from "asd" to "asda" is not allowed with the current mapping.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.