Я создаю схему с отображением спящего режима. Но по какой-то причине сопоставление от одного к одному не генерируется должным образом. Вот мои классы:
@Entity
@Table(name = "resturant")
public class Restaurant {
private Integer restid;
private String restaurantName;
private Foursquare foursquare;
@Id
@Column(name = "restid")
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId() {
return restid;
}
public void setId(Integer id) {
this.restid = id;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "restaurant", cascade = CascadeType.ALL)
public Foursquare getFoursquare() {
return foursquare;
}
public void setFoursquare(Foursquare foursquare) {
this.foursquare = foursquare;
}
@Column(name = "restname")
public String getRestaurantName() {
return restaurantName;
}
public void setRestaurantName(String restaurantName) {
this.restaurantName = restaurantName;
}
}
а также,
@Entity
@Table(name = "foursquare")
public class Foursquare {
private Integer foursquareid;
private Restaurant restaurant;
@Id
@Column(name = "fsid")
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getFoursquareid() {
return foursquareid;
}
public void setFoursquareid(Integer foursquareid) {
this.foursquareid = foursquareid;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Restaurant getRestaurant() {
return restaurant;
}
public void setRestaurant(Restaurant restaurant) {
this.restaurant = restaurant;
}
}
Мой hbm файл выглядит так:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- You need to complete the configuration here. This is just a sample,
you should use a connection pool -->
<property name="connection.url">jdbc:mysql://localhost:3306/menus3</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.jdbc.batch_size">50</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="Restaurant" />
<mapping class="Foursquare" />
</session-factory>
</hibernate-configuration>
Вот мой класс HibernateUtil:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Я запускаю простой класс для создания схемы, просто загружая конфигурацию:
public class Test {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.close();
}
}
Это должно создать внешний ключ restid в таблице Foursquare, но это не так. Sql выглядит так:
Hibernate: drop table if exists foursquare
Hibernate: drop table if exists resturant
Hibernate: create table foursquare (fsid integer not null auto_increment, idinfoursquare varchar(255), primary key (fsid))
Hibernate: create table resturant (restid integer not null auto_increment, restname varchar(255), staddress varchar(255), primary key (restid))
Может ли кто-нибудь указать, почему одно-одно сопоставление не отражается в моей БД? Почему колонка внешнего ключа не создается?
Вы использовали @PrimaryKeyJoinColumn
. Аннотации @PrimaryKeyJoinColumn
говорят, что первичный ключ объекта используется как значение внешнего ключа для связанного объекта. Таким образом, внешний ключ не генерируется. Чтобы создать внешний ключ, вы должны удалить @PrimaryKeyJoinColumn
@PrimaryKeyJoinColumn.
@OneToOne(fetch = FetchType.LAZY)
//@PrimaryKeyJoinColumn Remove this annotation.
public Restaurant getRestaurant() {
return restaurant;
}