0

I have an issue with one of my One-To-Many relationships. My problem is when I add a Tenant into an Apartment it doesn't set the column value in the Tenant to the ApartmentID. The thing is I have the exact same relationship with other classes and they are working fine... Does anyone have an idea why it's not wotking? Thanks

Apartment :

@Entity
public class Apartment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ApartmentID",unique = true, nullable = false)
    public int apartmentID;

    @OneToMany(mappedBy = "apartment", cascade = CascadeType.ALL)
    private List<Tenant> tenants;
}

Tenant :

@Entity
public class Tenant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="TenantID",unique = true, nullable = false)
    public int tenantID;

    @ManyToOne
    @JoinColumn(name = "ApartmentID")
    private Apartment apartment;
}
Nicolas Sagala Beaucage
  • 1,229
  • 1
  • 11
  • 23

3 Answers3

0

You don't show all your code here. So that i'm not sure to get your issues exactly. However, i just follow the post Hibernate Many to One Bidirectional Mapping Annotation Example and build project with your entities.

Here is main class that i add a Tenant into an Apartment.

public static void main(String[] args) {

        Tenant tenant = new Tenant();
        Apartment apartment = new Apartment();
        tenant.setApartment(apartment);
        List<Tenant> tenants = new ArrayList<Tenant>();
        tenants.add(tenant);
        apartment.setTenants(tenants);

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.persist(apartment);
        session.getTransaction().commit();

        session.close();
    }

Hibernate configuration

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">javabycode</property>
        <property name="hibernate.connection.password">mypassword</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javabycode</property>
        <property name="show_sql">false</property>
        <property name="hbm2ddl.auto">update</property>                
        <property name="format_sql">false</property>
        <mapping class="com.javabycode.hibernate.model.Tenant"/>
        <mapping class="com.javabycode.hibernate.model.Apartment"/>        
    </session-factory>
</hibernate-configuration>

Hibernate Util:

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Session Factory could not be created." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

It's work fine! The ApartmentID is already assigned a value in Tanent table.

David Pham
  • 1,673
  • 19
  • 17
  • The thing is that you are setting the value to each side and I don't want to do that. If I do apartment.setTenants() and persist/merge it I should have the tenant updated with the apartment in its field but I don't. What's weird here is that I also have Housing and Landlord which has a one to many relationship and it's working flawlessly. I can add pastebins of my models if you want but I'm sure that everything is fine – Nicolas Sagala Beaucage Oct 31 '16 at 05:55
0

In your bi-directional relationship Tenant is the owner of the relationship. Since you are persisting Apartment you have to manually set the apartment of tenant. If you want to get rid of manual setting change your @OneToMany as follows:

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="ApartmentID",referencedColumnName="ApartmentID")
private List<Tenant> tenants;

By the way, with your current sample if you are persisting tenant with apartment; apartment will be automatically persisted.

nickmesi
  • 180
  • 7
0
**please refer the example you will get an idea**

--------------------------------------------------------

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private List<Address> addresses;
}

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String street;
    private int houseNumber;
    private String city;
    private int zipCode;
    @ManyToOne(fetch = FetchType.LAZY)
    private Person person;
}