简体   繁体   中英

Hibernate OneToMany table not being updated

I have table Animal with OneToMany mapping to table EventAnimal:

    @OneToMany(mappedBy = "animal")
    public Set<EventAnimal> getEventAnimals() {
        return eventAnimals;
    }

Table EventAnimal looks like this

 @Entity
@Table(name = "eventAnimal")
public class EventAnimal {
    @Id
    int id;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "userEvent_id")
    UserEvent userEvent;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "animal_id", nullable=false)
    Animal animal;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "eventAnimalClass_id")
    EventAnimalClass eventAnimalClass;
}

When I add Event animal to animal and save animal, database is not being updated:

        //Create EventAnimal object, set properties
        eventAnimal.setUserEvent(newEvent);
        eventAnimal.setAnimal(animal);
        animal.getEventAnimals().add(eventAnimal);
        animalPersistenceService.saveAnimal(animal);

What am I doing wrong? When I try inserting Event animal, like eventAnimalDao.insert(eventAnimal); instead of

animalPersistenceService.saveAnimal(animal);

I get exception that "animal_id" does not have default value even though I set it.

What is your ID generation strategy? Are you generating the ids by yourself or you will leave this to the DB? If it will be database put:

@GeneratedValue(strategy=GenerationType.AUTO)

You may want to update the key to Integer instead of int too but don`t think this is the problem.

Also if you want to add event in animal and expect to persist it update your mapping to:

@OneToMany(mappedBy = "animal", cascade = CascadeType.ALL)

I have table Company with OneToMany mapping to table Customer:

//bi-directional many-to-one association to Customer
@OneToMany(mappedBy="company")
private Set<Customer> customer;

I have mapped from tis format:

//bi-directional many-to-one association to Company
    @ManyToOne
@JoinColumn(name="company_id")
private Company company;

I have use this code, Sucessfully add,edit and delete function is working.

Add function :

Customer customer = new Customer();
Company company = new Company();

company.setCompanyId(intCompanyId);
customer.setCompany(company);

I resolved the problem. It was rather silly mistake - script didn't remove one foreign key from table and I didn't care to look into SQL table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM