powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Составной ключ аннотациями EJB3
5 сообщений из 5, страница 1 из 1
Составной ключ аннотациями EJB3
    #34313812
Фотография Кувалдин Роман
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Здравствуй, всезнающий All. Как сделать составной ключ при помощи EJB3-аннотаций?

Допустим, есть класс User (USERS<ID, LOGIN, PASSWORD>), класс Resource(RESOURCES<ID, NAME, DESCRIPTION>), и табличка USERS_PERMISSIONS<USER_ID,PERMISSION_ID,PERMISSION_TYPE>

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
 package  ru.licvidator.entries;

 import  java.util.*;
 import  javax.persistence.*;

@Entity
@Table(name="USERS")
 public   class  User  extends  ContinousNumeratedEntry {
     private  String login;
     private  String password;
     public  User() {
    }
    
     public  User(String login, String password) {
         this ();
        setLogin(login);
        setPassword(password);
    }
    
     public  String getLogin() {
         return  login;
    }
    
     public   void  setLogin(String login) {
         this .login = login;
    }
    
     public  String getPassword() {
         return  password;
    }
    
     public   void  setPassword(String password) {
         this .password = password;
    }
}
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
 package  ru.licvidator.entries;

 import  java.util.*;
 import  javax.persistence.*;

@Entity
@Table(name="RESOURCES")
 public   class  Resource  extends  ContinousNumeratedEntry {
     private  String name;
     private  String description;
     public  Resource() {
    }
    
     public  String getName() {
         return  name;
    }
    
     public   void  setName(String name) {
         this .name = name;
    }
    
     public  String getDescription() {
         return  description;
    }
    
     public   void  setDescription(String description) {
         this .description = description;
    }
}

Как будет выглядеть описание класса, который позволит маппить табличку USERS_PERMISSIONS вышеприведенного вида?

П.С. Класс ContinousNumeratedEntry используется для реализации сквозной нумерации. Из него в таблицы наследуется поле ID.


=====================================
Страну, в которой все ходят на бровях,
на колени не поставишь...
=====================================
...
Рейтинг: 0 / 0
Составной ключ аннотациями EJB3
    #34313878
Фотография Timm
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
Составной ключ аннотациями EJB3
    #34315429
Arcadie
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
6.3.4. Primary-Key Classes and Composite Keys
Sometimes relational mappings require a primary key to be composed of multiple persistent properties. For instance, let's say that our relational model specified that our Customer entity should be identified by both its last name and its Social Security number instead of an autogenerated numeric key. These are called composite keys. The Java Persistence specification provides multiple ways to map this type of model. One is through the @javax.persistence.IdClass annotation; the other is through the @javax.persistence.EmbeddedId annotation.

6.3.4.1. @IdClass
The first way to define a primary-key class (and, for that matter, composite keys) is to use the @IdClass annotation. Your bean class does not use this primary-key class internally, but it does use it to interact with the entity manager when finding a persisted object through its primary key. @IdClass is a class-level annotation and specifies what primary-key class you should use when interacting with the entity manager.

@Target(TYPE)
@Retention(RUNTIME)
public @interface IdClass
{
Class value( );
}



In your bean class, you designate one or more properties that make up your primary key, using the @Id annotation. These properties must map exactly to properties in the @IdClass. Let's look at changing our Customer bean class to have a composite key made up of last name and Social Security number. First, let's define our primary-key class:

package com.titan.domain;

public class CustomerPK
implements java.io.Serializable {
private String lastName;
private long ssn;

public CustomerPK( ) {}

public CustomerPK(String lastName, long ssn)
{
this.lastName = lastName;
this.ssn = ssn;
}

public String getLastName( ) { return this.lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }

public long getSsn( ) { return ssn; }
public void setSsn(long ssn) { this.ssn = ssn; }

public boolean equals(Object obj)
{
if (obj == this) return true;
if (!(obj instanceof CustomerPK)) return false;
CustomerPK pk = (CustomerPK)obj;
if (!lastName.equals(pk.lastName)) return false;
if (ssn != pk.ssn) return false;
return true;
}

public int hashCode( )
{
return lastName.hashCode( ) + (int)ssn;
}
}



The primary-key class must meet these requirements:

It must be serializable.

It must have a public no-arg constructor.

It must implement the equals( ) and hashCode( ) methods.

Our Customer bean must have the same exact properties as the CustomerPK class, and these properties are annotated with multiple @Id annotations:

package com.titan.domain;

import javax.persistence.*;

@Entity
@IdClass(CustomerPK.class)
public class Customer implements java.io.Serializable {
private String firstName;
private String lastName;
private long ssn;

public String getFirstName( ) { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }

@Id
public String getLastName( ) { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }

@Id
public long getSsn( ) { return ssn; }
public void setSsn(long ssn) { this.ssn = ssn; }
}



Primary-key autogeneration is not supported for composite keys and primary-key classes. You will have to manually create the key values in code.






Let's now look at the XML mapping equivalent to @IdClass:

<entity-mappings>
<entity class="com.titan.domain.Customer" access="PROPERTY">
<id-class>com.titan.domain.CustomerPK</id-class>
<attributes>
<id name="lastName"/>
<id name="ssn"/>
</attributes>
</entity>
</entity-mappings>



The <id-class> element is a subelement of <entity>, and its value is the fully qualified class name of the primary-key class. Notice also that multiple <id> elements for each property map to the primary-key class.

The primary-key class is used whenever you are querying for the Customer:

CustomerPK pk = new CustomerPK("Burke", 9999999);
Customer cust = entityManager.find(Customer.class, pk);



Whenever you call an EntityManager method like find( ) or getreference( ), you must use the primary key class to identify the entity.
...
Рейтинг: 0 / 0
Составной ключ аннотациями EJB3
    #34316016
Фотография Кувалдин Роман
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Да, оно. Благодарю всех откликнувшихся.


=====================================
Страну, в которой все ходят на бровях,
на колени не поставишь...
=====================================
...
Рейтинг: 0 / 0
Составной ключ аннотациями EJB3
    #34708990
ncr
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ncr
Гость
Здравствуйте.

Подскажите пожалуйста, как в persistence.xml указать что сущность использует составной ключ.
Пока составного ключа нет, все нормально работает:

<?xml version="1.0" encoding="windows-1251" ?>
<persistence>
<persistence-unit name="oracleTest">
<jta-data-source>java:/jdbc/oraTest</jta-data-source>
<class>test.ejb3.entity.FirstEntity</class>
<class>test.entity.SecondEntity</class>
<class>test.ejb3.entity.ThirdEntity</class>
<exclude-unlisted-classes/>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
</properties>
</persistence-unit>
</persistence>

А когда появляется например таблица FourthEntity, имеющая составной ключ описанный в FourthEntityPK, начинаются проблемы.
...
Рейтинг: 0 / 0
5 сообщений из 5, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Составной ключ аннотациями EJB3
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]