miércoles, 30 de mayo de 2018

Hibernate Road 2

Guardando Collecciones, @ElementCollection


Una alternativa para no tener que crear varios campo de address, es crear un campo de tipo lista de Address, o una Colección, esto se logra con la anotacion @ElementCollection

UserDetails.java
...@Entity
@Table (name="USER_DETAILS")
public class UserDetails {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int userId;
    private String userName;
    @Temporal (TemporalType.DATE)
    private Date joinedDate;
    @ElementCollection
    private Set<Address> listOfAddresses = new HashSet();

    @Lob
    private String description;
...


El programa de prueba HibernateTest.java, que prepara y carga los campos de las entidades quedaría de la siguiente manera.

public class HibernateTest {

    public static void main(String[] args) {
        Address addr1 = new Address();
        addr1.setStreet("calle 10");
        addr1.setCity("Mexico");
        addr1.setState("DF");
        addr1.setPinCode("32123");
      
        Address addr2 = new Address();
        addr2.setStreet("Miguel Hidalgo");
        addr2.setCity("San Miguel de Allende");
        addr2.setState("Guanajuato");
        addr2.setPinCode("00011");
      
        Address officeAddr = new Address();
        officeAddr.setStreet("Paseo de la Reforma");
        officeAddr.setCity("Mexico");
        officeAddr.setState("D.F");
        officeAddr.setPinCode("01223");
              
        UserDetails userDetails = new UserDetails();
        UserDetails userDetails2 = new UserDetails();
      
        userDetails.setUserName("Primer Usuario");
        userDetails.setJoinedDate(new Date());
        userDetails.setDescription("Primer Usuario Descripcion");
        userDetails.getListOfAddresses().add(addr1);
        userDetails.getListOfAddresses().add(officeAddr);

      
        userDetails2.setUserName("Segundo Usuario");
        userDetails2.getListOfAddresses().add(addr2);
      
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(userDetails);
        session.save(userDetails2);
        session.getTransaction().commit();
        session.close();
        //sessionFactory.close();
    }


Al ejecutar esta prueba, Hibernate en la consola reporta crear dos tablas, ademas de la de sequencia.

...
Hibernate: drop table if exists hibernate_sequence
...
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists UserDetails_listOfAddresses
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
...
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, description longtext, joinedDate date, userName varchar(255), primary key (userId)) engine=MyISAM
Hibernate: create table UserDetails_listOfAddresses (UserDetails_userId integer not null, city varchar(255), pinCode varchar(255), state varchar(255), street varchar(255)) engine=MyISAM
Hibernate: alter table UserDetails_listOfAddresses add constraint FK6wx73ocb6j0mymo1jkcv0o3wm foreign key (UserDetails_userId) references USER_DETAILS (userId)
...

Podemos ver que crea la llave foranea.

Tabla USER_DETAILS

userId description joinedDate userName
1 Primer Usuario Descripcion 2018-05-28 Primer Usuario
2 NULL NULL Segundo Usuario

Tabla UserDetails_listOfAddresses
UserDetails_userId city pinCode state street
1 Mexico 32123 DF calle 10
1 Mexico 01223 D.F Paseo de la Reforma
2 San Miguel de Allende 00011 Guanajuato Miguel Hidalgo

Podemos interpretar que para el usuario Id 1 le corresponden 2 Address, mientras que para el usuario id 2, solo un Address.


@OneToOne, con Entidades UserDetails y Vehicle

Dejando atrás las Colecciones, haremos una relación de dos entidades, UserDetails y Vehicle. Para esto se agregara una propiedad vehicle la cual es una entidad por si misma, y para hacer la relación de entidades por medio de la anotación @OneToOne y @JoinColumn.
UserDetails.java
@Entity
@Table (name="USER_DETAILS")
public class UserDetails {
       @Id @GeneratedValue(strategy=GenerationType.AUTO)
       private int userId;
       private String userName;
       @OneToOne
       @JoinColumn(name="VEHICLE_ID")
       private Vehicle vehicle;
…Setters y Getters

La entidad vehicle, tiene una llave con autogeneración de secuencia.
Vehicle.java
@Entity
public class Vehicle {
    @Id @GeneratedValue(generator="vehicle-gen",strategy=GenerationType.AUTO)
    @GenericGenerator(name="vehicle-gen",strategy="sequence",
       parameters = {
                    @Parameter(name="sequence_name", value="seq_vehicle") }
    )
       private int vehicleId;
       private String vehicleName;
setters y getters
El programa HibernateTest.java carga e inicializa con valores de prueba estas dos entidades.
HibernateTest.java
public class HibernateTest {

       public static void main(String[] args) {
             UserDetails userDetails = new UserDetails();
             userDetails.setUserName("Primer Usuario");
             UserDetails userDetails2 = new UserDetails();
             userDetails2.setUserName("Segundo Usuario");
            
             Vehicle vehicle = new Vehicle();
             vehicle.setVehicleName("Carrito");
             Vehicle vehicle2 = new Vehicle();
             vehicle2.setVehicleName("Super Auto");
            
             userDetails.setVehicle(vehicle);
             userDetails2.setVehicle(vehicle2);
            
             SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
             Session session = sessionFactory.openSession();
             session.beginTransaction();
             session.save(userDetails);
             session.save(vehicle);
             session.save(userDetails2);
             session.save(vehicle2);
            
             session.getTransaction().commit();
             session.close();
             //sessionFactory.close();
       }

La ejecución de HibernateTest.java muestra en consola por parte de Hibernate como crea las tablas y sus tablas de secuencias. Se observa que crea para userdetails una llave foránea hacia vehicle.
Hibernate: drop table if exists hibernate_sequence
may 30, 2018 11:58:21 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@f80945f] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table if exists seq_vehicle
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists Vehicle
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
may 30, 2018 11:58:21 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@22ffa91a] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table seq_vehicle (next_val bigint) engine=MyISAM
Hibernate: insert into seq_vehicle values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, userName varchar(255), VEHICLE_ID integer, primary key (userId)) engine=MyISAM
Hibernate: create table Vehicle (vehicleId integer not null, vehicleName varchar(255), primary key (vehicleId)) engine=MyISAM
Hibernate: alter table USER_DETAILS add constraint FKqweooss4hgrydsdo0xj7m6p40 foreign key (VEHICLE_ID) references Vehicle (vehicleId)
La Tabla vehicle
vehicleId vehicleName
1 Carrito
2 Super Auto


La table UserDetails
userId userName VEHICLE_ID
1 Primer Usuario 1
2 Segundo Usuario 2


@OneToMany

Establescamos una relación uno a muchos, es decir, por un usuario, Habra muchos vehiculos.

UserDetails.java
@Entity
@Table (name="USER_DETAILS")
public class UserDetails {
       @Id @GeneratedValue(generator="vehicle-gen",strategy=GenerationType.AUTO)
       @GenericGenerator(name="vehicle-gen",strategy="sequence",
                                         parameters={@Parameter(name="sequence_name",value="seq_vehicle")}
                                  )
       private int userId;
       private String userName;
       @OneToMany
       private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();

Al ejecutar HibernateTest.java, en la consola hibernate reporta que crea una table llamada USER_DETAILS_Vehicle que hace un mapeo entre los registros de la table UserDetails y Vehicle.
Hibernate: drop table if exists hibernate_sequence
Hibernate: drop table if exists seq_vehicle
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists USER_DETAILS_Vehicle
Hibernate: drop table if exists Vehicle
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table seq_vehicle (next_val bigint) engine=MyISAM
Hibernate: insert into seq_vehicle values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, userName varchar(255), primary key (userId)) engine=MyISAM
Hibernate: create table USER_DETAILS_Vehicle (UserDetails_userId integer not null, vehicle_vehicleId integer not null) engine=MyISAM
Hibernate: create table Vehicle (vehicleId integer not null, vehicleName varchar(255), primary key (vehicleId)) engine=MyISAM
Hibernate: alter table USER_DETAILS_Vehicle add constraint UK_7fhk3kle7eb0p5vqydj1eugt7 unique (vehicle_vehicleId)
Hibernate: alter table USER_DETAILS_Vehicle add constraint FKd6kp2c4oltmpsg6g9d8u15ymw foreign key (vehicle_vehicleId) references Vehicle (vehicleId)
Hibernate: alter table USER_DETAILS_Vehicle add constraint FKbdrxqw3j8dovf9npdkrfkpc3u foreign key (UserDetails_userId) references USER_DETAILS (userId)
Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into Vehicle (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into Vehicle (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into USER_DETAILS_Vehicle (UserDetails_userId, vehicle_vehicleId) values (?, ?)
Hibernate: insert into USER_DETAILS_Vehicle (UserDetails_userId, vehicle_vehicleId) values (?, ?)

Tabla Vehicle
vehicleId vehicleName
1 carrito
2 Audi

Table UserDetails
userId userName
1 Primer Usuario
2 Segundo Usuario

Table USER_DETAILS_Vehicle
UserDetails_userId vehicle_vehicleId
1 1
1 2



@OneToMany @JoinColumn(name=”VEHICLE_ID”)


Ahora establescamos una relacion uno a muchos, es decir, por un usuario, Habra muchos vehiculos.
pero con un campo extra sin necesidad de crear una tabla extra de relación.

UserDetails.java
@Entity
@Table (name="USER_DETAILS")
public class UserDetails {
       @Id @GeneratedValue(generator="vehicle-gen",strategy=GenerationType.AUTO)
       @GenericGenerator(name="vehicle-gen",strategy="sequence",
                                         parameters={@Parameter(name="sequence_name",value="seq_vehicle")}
                                  )
       private int userId;
       private String userName;
       @OneToMany
       @JoinColumn(name="VEHICLE_ID")
       private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
       setters y getters…
Las Anotaciones @OneToMany, y @JoinColumn se encargan de hacer esta relación.
HibernateTest.java cargará datos a userDetail y vehicle, al correrlo, hibernate reporta en la consola
Hibernate: drop table if exists hibernate_sequence
may 30, 2018 5:41:34 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@424ebba3] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table if exists seq_vehicle
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists Vehicle
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
may 30, 2018 5:41:34 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@4bff64c2] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table seq_vehicle (next_val bigint) engine=MyISAM
Hibernate: insert into seq_vehicle values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, userName varchar(255), primary key (userId)) engine=MyISAM
Hibernate: create table Vehicle (vehicleId integer not null, vehicleName varchar(255), VEHICLE_ID integer, primary key (vehicleId)) engine=MyISAM
Hibernate: alter table Vehicle add constraint FK1rpisx3grg2fqb9qg9ioj8kvv foreign key (VEHICLE_ID) references USER_DETAILS (userId)
may 30, 2018 5:41:34 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@2101b44a'
Wed May 30 17:41:35 CDT 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into Vehicle (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into Vehicle (vehicleName, vehicleId) values (?, ?)
Hibernate: update Vehicle set VEHICLE_ID=? where vehicleId=?
Hibernate: update Vehicle set VEHICLE_ID=? where vehicleId=?

La Tabla Vehicle crea una llave foranea a la table UserDetails

Tabla Vehicle
vehicleId vehicleName VEHICLE_ID
1 carrito 1
2 Audi 1

Table UserDetails
userId userName
1 Primer Usuario
2 Segundo Usuario


En las tablas observamos que para el primer usuario, le corresponden varios vehiculos.


@OneToMany @JoinTable(name=”USER_VEHICLE”, joinColumns=@JoinColumn(name=”USER_ID”),                                                               inverseJoinColumns=@JoinColumn(name=”VEHICLE_ID”))


@Entity
@Table (name="USER_DETAILS")
public class UserDetails {
       @Id @GeneratedValue(generator="vehicle-gen",strategy=GenerationType.AUTO)
       @GenericGenerator(name="vehicle-gen",strategy="sequence",
                                         parameters={@Parameter(name="sequence_name",value="seq_vehicle")}
                                  )
       private int userId;
       private String userName;
       @OneToMany
       @JoinTable(name="USER_VEHICLE",joinColumns=@JoinColumn(name="USER_ID"),
                    inverseJoinColumns=@JoinColumn(name="VEHICLE_ID"))
       private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();

Mensajes de consola al ejecutar HibernateTest.java:

Hibernate: drop table if exists hibernate_sequence
Hibernate: drop table if exists seq_vehicle
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists USER_VEHICLE
Hibernate: drop table if exists Vehicle
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table seq_vehicle (next_val bigint) engine=MyISAM
Hibernate: insert into seq_vehicle values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, userName varchar(255), primary key (userId)) engine=MyISAM

Hibernate: create table USER_VEHICLE (USER_ID integer not null, VEHICLE_ID integer not null) engine=MyISAM

Hibernate: create table Vehicle (vehicleId integer not null, vehicleName varchar(255), primary key (vehicleId)) engine=MyISAM

Hibernate: alter table USER_VEHICLE add constraint UK_96us7rjdfqie54lp1d7tcl8fg unique (VEHICLE_ID)

Hibernate: alter table USER_VEHICLE add constraint FKav7c1bp55pcqm52pwpq55rpmc foreign key (VEHICLE_ID) references Vehicle (vehicleId)

Hibernate: alter table USER_VEHICLE add constraint FKay5vn6ovfwhmoi2w1wrxxry0 foreign key (USER_ID) references USER_DETAILS (userId)

Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into Vehicle (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into Vehicle (vehicleName, vehicleId) values (?, ?)
Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?)
Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?)

Tabla Vehicle
vehicleId vehicleName
1 carrito
2 Audi

Tabla USER_DETAILS
userId userName
1 Primer Usuario
2 Segundo Usuario

tabla USER_VEHICLE

USER_ID VEHICLE_ID
1 1
1 2


@ManyToOne


Establescamos una relación ahora de muchos a uno, desde el punto de vista de Vehicle, esto es segirá habiendo más vehículos por usuario, pero ahora se modificará la entidad Vehicle. Que en este caso será redundante. Esto crea en la tabla vehicle un campo que hace referencia a userid.

@Entity
public class Vehicle {
       @Id @GeneratedValue(strategy=GenerationType.AUTO)
       private int vehicleId;
       private String vehicleName;
       @ManyToOne
       private UserDetails user;

HibernateTest.java le asigna un valor al usuario en vehicle.
public class HibernateTest {

       public static void main(String[] args) {
             UserDetails userDetails = new UserDetails();
             UserDetails userDetails2 = new UserDetails();
            
             Vehicle vehicle1 = new Vehicle();
             vehicle1.setVehicleName("carrito");
             Vehicle vehicle2 = new Vehicle();
             vehicle2.setVehicleName("Audi");
                          
             userDetails.setUserName("Primer Usuario");
             userDetails.getVehicle().add(vehicle1);
             userDetails.getVehicle().add(vehicle2);
             userDetails2.setUserName("Segundo Usuario");
            
             vehicle1.setUser(userDetails);
             vehicle2.setUser(userDetails);
            
             SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
             Session session = sessionFactory.openSession();
             session.beginTransaction();
             session.save(userDetails);
             session.save(userDetails2);
             session.save(vehicle1);
             session.save(vehicle2);
             session.getTransaction().commit();
             session.close();
            
             //sessionFactory.close();
       }


El mensaje en consola de hibernate muestra que crea la tabla Vehicle con un campo extra userId.


Hibernate: drop table if exists seq_vehicle
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists USER_VEHICLE
Hibernate: drop table if exists Vehicle
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table seq_vehicle (next_val bigint) engine=MyISAM
Hibernate: insert into seq_vehicle values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, userName varchar(255), primary key (userId)) engine=MyISAM
Hibernate: create table USER_VEHICLE (USER_ID integer not null, VEHICLE_ID integer not null) engine=MyISAM
Hibernate: create table Vehicle (vehicleId integer not null, vehicleName varchar(255), user_userId integer, primary key (vehicleId)) engine=MyISAM

Hibernate: alter table USER_VEHICLE add constraint UK_96us7rjdfqie54lp1d7tcl8fg unique (VEHICLE_ID)
Hibernate: alter table USER_VEHICLE add constraint FKav7c1bp55pcqm52pwpq55rpmc foreign key (VEHICLE_ID) references Vehicle (vehicleId)
Hibernate: alter table USER_VEHICLE add constraint FKay5vn6ovfwhmoi2w1wrxxry0 foreign key (USER_ID) references USER_DETAILS (userId)
Hibernate: alter table Vehicle add constraint FKd7stcl2wpnsvhruhwkr4isucp foreign key (user_userId) references USER_DETAILS (userId)

Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from seq_vehicle for update
Hibernate: update seq_vehicle set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)
Hibernate: insert into Vehicle (user_userId, vehicleName, vehicleId) values (?, ?, ?)
Hibernate: insert into Vehicle (user_userId, vehicleName, vehicleId) values (?, ?, ?)
Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?)
Hibernate: insert into USER_VEHICLE (USER_ID, VEHICLE_ID) values (?, ?)

Tabla Vehicle
vehicleId vehicleName user_userId
1 carrito 1
2 Audi 1

@OneToMany con MappedBy y @ManyToOne @JoinColumn


Con estas anotaciones se evita la creación de una tercera tabla que haga la interrelación entre UserDetails y Vehicle, ya que se creara un campo en Vehicle con referencia a UserId.

UserDetails.java

@Entity
@Table (name="USER_DETAILS")
public class UserDetails {
       @Id @GeneratedValue(generator="vehicle-gen",strategy=GenerationType.AUTO)
       @GenericGenerator(name="vehicle-gen",strategy="sequence",
                                         parameters={@Parameter(name="sequence_name",value="seq_vehicle")}
                                  )
       private int userId;
       private String userName;
       @OneToMany(mappedBy="user")

       private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
…setters y getters…


Y en Vehicle.java



@Entity
public class Vehicle {
       @Id @GeneratedValue(strategy=GenerationType.AUTO)
       private int vehicleId;
       private String vehicleName;
       @ManyToOne

       @JoinColumn(name="USER_ID")

       private UserDetails user;
…setters y getters…


La ejecucion the HibernateTest.java en consola nos reporta lo que hibernate hace.


Hibernate: drop table if exists hibernate_sequence
Hibernate: drop table if exists seq_vehicle
Hibernate: drop table if exists USER_DETAILS
Hibernate: drop table if exists Vehicle
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table seq_vehicle (next_val bigint) engine=MyISAM
Hibernate: insert into seq_vehicle values ( 1 )
Hibernate: create table USER_DETAILS (userId integer not null, userName varchar(255), primary key (userId)) engine=MyISAM

Hibernate: create table Vehicle (vehicleId integer not null, vehicleName varchar(255), USER_ID integer, primary key (vehicleId)) engine=MyISAM

Hibernate: alter table Vehicle add constraint FKmheo4c5byfserchvn74kyrru9 foreign key (USER_ID) references USER_DETAILS (userId)



Table UserDetails
userId userName
1 Primer Usuario
2 Segundo Usuario

Tabla Vehicle
vehicleId vehicleName USER_ID
1 carrito 1
2 Audi 1

fin de texto.

No hay comentarios:

Publicar un comentario