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.