С Новым годом! Форум программистов, компьютерный форум, киберфорум
Java EE (J2EE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 13.04.2010
Сообщений: 19

JPA + Hibernate; @ManyToOne

09.05.2013, 22:15. Показов 1149. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте!

Есть первый класс сущности:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.pb.webdiagramiq.domain;
     
    import javax.persistence.Column;
    import javax.persistence.Id;
    import javax.persistence.Entity;
    import javax.persistence.Table;
     
    import java.io.Serializable;
     
    /**
    *
    * @author Giggs13
    * Класс сущности.
    */
    @Entity
    @Table(name = "PMN_REPORTS_BONUS_METHOD")
    public class PmnReportsBonusMethod implements Serializable {
     
    private String reportMethod;
    private String ReportMethodName;
    public PmnReportsBonusMethod() {
    }
     
    public PmnReportsBonusMethod(String reportMethod, String ReportMethodName) {
    this.reportMethod = reportMethod;
    this.ReportMethodName = ReportMethodName;
    }
     
    @Id
    @Column(name = "REPORT_METHOD")
    public String getReportMethod() {
    return reportMethod;
    }
     
    public void setReportMethod(String reportMethod) {
    this.reportMethod = reportMethod;
    }
     
    @Column(name = "REPORT_METHOD_NAME")
    public String getReportMethodName() {
    return ReportMethodName;
    }
     
    public void setReportMethodName(String ReportMethodName) {
    this.ReportMethodName = ReportMethodName;
    }
     
    @Override
    public String toString() {
    return "PmnReportsBonusMethod{" + "reportMethod=" + reportMethod + ", ReportMethodName=" + ReportMethodName + '}';
    }
    }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Есть второй класс сущности:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.pb.webdiagramiq.domain;
     
    import javax.persistence.Column;
    import javax.persistence.Id;
    import javax.persistence.Entity;
    import javax.persistence.Table;
     
    import java.io.Serializable;
     
    /**
    *
    * @author Giggs13
    * Класс сущности.
    */
    @Entity
    @Table(name = "PMN_REPORTS_BONUS_RT_TYPE")
    public class PmnReportsBonusRtType implements Serializable {
     
    private String reportType;
    private String ReportTypeName;
    public PmnReportsBonusRtType() {
    }
     
    public PmnReportsBonusRtType(String reportType, String ReportTypeName) {
    this.reportType = reportType;
    this.ReportTypeName = ReportTypeName;
    }
     
    @Id
    @Column(name = "REPORT_TYPE")
    public String getReportType() {
    return reportType;
    }
     
    public void setReportType(String reportType) {
    this.reportType = reportType;
    }
     
    @Column(name = "REPORT_TYPE_NAME")
    public String getReportTypeName() {
    return ReportTypeName;
    }
     
    public void setReportTypeName(String ReportTypeName) {
    this.ReportTypeName = ReportTypeName;
    }
     
    @Override
    public String toString() {
    return "PmnReportsBonusRtType{" + "reportType=" + reportType + ", ReportTypeName=" + ReportTypeName + '}';
    }
    }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Второй класс взаимосвязан с 3-м:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.pb.webdiagramiq.domain;
     
    import javax.persistence.Column;
    import javax.persistence.Id;
    import javax.persistence.Entity;
    import javax.persistence.Table;
    import javax.persistence.ManyToOne;
    import javax.persistence.JoinColumn;
     
    import java.io.Serializable;
     
    /**
    *
    * @author Giggs13
    * Класс сущности.
    */
    @Entity
    @Table(name = "PMN_REPORTS_BONUS_RT_ID")
    public class PmnReportsBonusRtId implements Serializable {
    private String reportId;
    private String reportType;
    private String reportName;
    private PmnReportsBonusRtType pmnReportsBonusRtType;
     
    public PmnReportsBonusRtId() {
    }
     
    public PmnReportsBonusRtId(String reportId, String reportType, String reportName, PmnReportsBonusRtType pmnReportsBonusRtType) {
    this.reportId = reportId;
    this.reportType = reportType;
    this.reportName = reportName;
    this.pmnReportsBonusRtType = pmnReportsBonusRtType;
    }
     
    @Id
    @Column(name = "REPORT_ID")
    public String getReportId() {
    return reportId;
    }
     
    public void setReportId(String reportId) {
    this.reportId = reportId;
    }
     
    @Column(name = "REPORT_TYPE", insertable = false, updatable = false)
    public String getReportType() {
    return reportType;
    }
     
    public void setReportType(String reportType) {
    this.reportType = reportType;
    }
     
    @Column(name = "REPORT_NAME")
    public String getReportName() {
    return reportName;
    }
     
    public void setReportName(String reportName) {
    this.reportName = reportName;
    }
     
    @ManyToOne
    @JoinColumn(name = "REPORT_TYPE")
    public PmnReportsBonusRtType getPmnReportsBonusRtType() {
    return pmnReportsBonusRtType;
    }
     
    public void setPmnReportsBonusRtType(PmnReportsBonusRtType pmnReportsBonusRtType) {
    this.pmnReportsBonusRtType = pmnReportsBonusRtType;
    }
     
    @Override
    public String toString() {
    return "PmnReportsBonusRtId{" + "reportId=" + reportId + ", reportType=" + reportType + ", reportName=" + reportName + ", pmnReportsBonusRtType=" + pmnReportsBonusRtType + '}';
    }
    }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
С 1-м и 3-м классами сущностей я делаю отношения @ManyToOne в классе первичного ключа, используемого затем в 4-м классе сущности. Вот класс первичного ключа:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.pb.webdiagramiq.domain.primarykey;
     
    import com.pb.webdiagramiq.domain.PmnReportsBonusRtId;
    import com.pb.webdiagramiq.domain.PmnReportsBonusMethod;
     
    import javax.persistence.Embeddable;
    import javax.persistence.ManyToOne;
    import javax.persistence.JoinColumn;
    import javax.persistence.PrimaryKeyJoinColumn;
    import javax.persistence.PrimaryKeyJoinColumns;
     
    import java.io.Serializable;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.FetchType;
    import javax.persistence.Transient;
     
    /**
    *
    * @author Giggs13
    * Класс первичного ключа для PmnReportsBonusRtMethodVid.
    */
    @Embeddable
    public class PmnReportsBonusRtMethodVidPK implements Serializable {
    private String reportId;
    private String reportMethod;
    private Integer reportMethodVid;
    private PmnReportsBonusRtId pmnReportsBonusRtId;
    private PmnReportsBonusMethod pmnReportsBonusMethod;
     
    public PmnReportsBonusRtMethodVidPK() {
    }
     
    public PmnReportsBonusRtMethodVidPK(String reportId, String reportMethod, Integer reportMethodVid, PmnReportsBonusRtId pmnReportsBonusRtId, PmnReportsBonusMethod pmnReportsBonusMethod) {
    this.reportId = reportId;
    this.reportMethod = reportMethod;
    this.reportMethodVid = reportMethodVid;
    this.pmnReportsBonusRtId = pmnReportsBonusRtId;
    this.pmnReportsBonusMethod = pmnReportsBonusMethod;
    }
    //@Transient
    @Column(name = "REPORT_ID")
    public String getReportId() {
    return reportId;
    }
     
    public void setReportId(String reportId) {
    this.reportId = reportId;
    }
    //@Transient
    @Column(name = "REPORT_METHOD")
    public String getReportMethod() {
    return reportMethod;
    }
     
    public void setReportMethod(String reportMethod) {
    this.reportMethod = reportMethod;
    }
     
    @Column(name = "REPORT_METHOD_VID")
    public Integer getReportMethodVid() {
    return reportMethodVid;
    }
     
    public void setReportMethodVid(Integer reportMethodVid) {
    this.reportMethodVid = reportMethodVid;
    }
     
    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "REPORT_ID", referencedColumnName = "REPORT_ID")
    public PmnReportsBonusRtId getPmnReportsBonusRtId() {
    return pmnReportsBonusRtId;
    }
     
    public void setPmnReportsBonusRtId(PmnReportsBonusRtId pmnReportsBonusRtId) {
    this.pmnReportsBonusRtId = pmnReportsBonusRtId;
    }
     
    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "REPORT_METHOD", referencedColumnName = "REPORT_METHOD")
    public PmnReportsBonusMethod getPmnReportsBonusMethod() {
    return pmnReportsBonusMethod;
    }
     
    public void setPmnReportsBonusMethod(PmnReportsBonusMethod pmnReportsBonusMethod) {
    this.pmnReportsBonusMethod = pmnReportsBonusMethod;
    }
     
    @Override
    public int hashCode() {
    int hash = 7;
    hash = 17 * hash + (this.reportId != null ? this.reportId.hashCode() : 0);
    hash = 17 * hash + (this.reportMethod != null ? this.reportMethod.hashCode() : 0);
    hash = 17 * hash + (this.reportMethodVid != null ? this.reportMethodVid.hashCode() : 0);
    hash = 17 * hash + (this.pmnReportsBonusRtId != null ? this.pmnReportsBonusRtId.hashCode() : 0);
    hash = 17 * hash + (this.pmnReportsBonusMethod != null ? this.pmnReportsBonusMethod.hashCode() : 0);
    return hash;
    }
     
    @Override
    public boolean equals(Object obj) {
    if (obj == null) {
    return false;
    }
    if (getClass() != obj.getClass()) {
    return false;
    }
    final PmnReportsBonusRtMethodVidPK other = (PmnReportsBonusRtMethodVidPK) obj;
    if ((this.reportId == null) ? (other.reportId != null) : !this.reportId.equals(other.reportId)) {
    return false;
    }
    if ((this.reportMethod == null) ? (other.reportMethod != null) : !this.reportMethod.equals(other.reportMethod)) {
    return false;
    }
    if (this.reportMethodVid != other.reportMethodVid && (this.reportMethodVid == null || !this.reportMethodVid.equals(other.reportMethodVid))) {
    return false;
    }
    if (this.pmnReportsBonusRtId != other.pmnReportsBonusRtId && (this.pmnReportsBonusRtId == null || !this.pmnReportsBonusRtId.equals(other.pmnReportsBonusRtId))) {
    return false;
    }
    return true;
    }
    @Override
    public String toString() {
    return "PmnReportsBonusRtMethodVidPK{" + "reportId=" + reportId + ", reportMethod=" + reportMethod + ", reportMethodVid=" + reportMethodVid + ", pmnReportsBonusRtId=" + pmnReportsBonusRtId + ", pmnReportsBonusMethod=" + pmnReportsBonusMethod + '}';
    }
    }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4-й класс сущности:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.pb.webdiagramiq.domain;
     
    import javax.persistence.Column;
    import javax.persistence.Id;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.Table;
    import javax.persistence.AttributeOverrides;
    import javax.persistence.AttributeOverride;
    import javax.persistence.Transient;
     
    import java.io.Serializable;
     
    import com.pb.webdiagramiq.domain.primarykey.PmnReportsBonusRtMethodVidPK;
     
    /**
    *
    * @author Giggs13
    * Класс сущности.
    */
    @Entity
    @Table(name = "PMN_REPORTS_BONUS_RT_METHOD_VID")
    public class PmnReportsBonusRtMethodVid implements Serializable {
    private String reportMethodVidName;
    private String flClose;
    private PmnReportsBonusRtMethodVidPK pmnReportsBonusRtMethodVidPK;
     
    public PmnReportsBonusRtMethodVid() {
    }
     
    public PmnReportsBonusRtMethodVid(String reportMethodVidName, String flClose, PmnReportsBonusRtMethodVidPK pmnReportsBonusRtMethodVidPK, PmnReportsBonusRtId pmnReportsBonusRtId, PmnReportsBonusMethod pmnReportsBonusMethod) {
    this.reportMethodVidName = reportMethodVidName;
    this.flClose = flClose;
    this.pmnReportsBonusRtMethodVidPK = pmnReportsBonusRtMethodVidPK;
    }
    @EmbeddedId
    @AttributeOverrides({
    @AttributeOverride(name = "reportId",
    column = @Column(name = "REPORT_ID")),
    @AttributeOverride(name = "reportMethod",
    column = @Column(name = "REPORT_METHOD")),
    @AttributeOverride(name = "reportMethodVid",
    column = @Column(name = "REPORT_METHOD_VID"))
    })
     
    @Transient
    public String getReportId() {
    return pmnReportsBonusRtMethodVidPK.getReportId();
    }
     
    public void setReportId(String reportId) {
    pmnReportsBonusRtMethodVidPK.setReportId(reportId);
    }
     
    @Transient
    public String getReportMethod() {
    return pmnReportsBonusRtMethodVidPK.getReportMethod();
    }
     
    public void setReportMethod(String reportMethod) {
    pmnReportsBonusRtMethodVidPK.setReportMethod(reportMethod);
    }
     
    @Transient
    public Integer getReportMethodVid() {
    return pmnReportsBonusRtMethodVidPK.getReportMethodVid();
    }
     
    public void setReportMethodVid(Integer reportMethodVid) {
    pmnReportsBonusRtMethodVidPK.setReportMethodVid(reportMethodVid);
    }
    @Id
    public PmnReportsBonusRtMethodVidPK getPmnReportsBonusRtMethodVidPK() {
    return pmnReportsBonusRtMethodVidPK;
    }
     
    public void setPmnReportsBonusRtMethodVidPK(PmnReportsBonusRtMethodVidPK pmnReportsBonusRtMethodVidPK) {
    this.pmnReportsBonusRtMethodVidPK = pmnReportsBonusRtMethodVidPK;
    }
    @Column(name = "REPORT_METHOD_VID_NAME")
    public String getreportMethodVidName() {
    return reportMethodVidName;
    }
     
    public void setreportMethodVidName(String reportMethodVidName) {
    this.reportMethodVidName = reportMethodVidName;
    }
     
    @Column(name = "FL_CLOSE")
    public String getFlClose() {
    return flClose;
    }
     
    public void setFlClose(String flClose) {
    this.flClose = flClose;
    }
     
    @Override
    public String toString() {
    return "PmnReportsBonusRtMethodVid{" + "reportMethodVidName=" + reportMethodVidName + ", flClose=" + flClose + ", pmnReportsBonusRtMethodVidPK=" + pmnReportsBonusRtMethodVidPK + '}';
    }
    }
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Выскакивает ошибка:
org.hibernate.MappingException: Repeated column in mapping for entity: com.pb.webdiagramiq.domain.PmnReportsBon usRtMethodVid column: REPORT_ID (should be mapped with insert="false" update="false")

Может ли кто-нибудь помочь, я уже пробывал как мог исправить код, но ничего не получается.. Спросить совершенно не у кого.. Заранее спасибо за любую помощь в решении моей проблемы!
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
09.05.2013, 22:15
Ответы с готовыми решениями:

ManyToOne in Hibernate
Здравствуйте. Помогите решить проблему... Я питаюсь реализовать связь в своем проект "ManytoOne". Коротко опишу функционал: есть...

Hibernate OneToMany, ManyToOne и тд
Добрый день. В очередной раз переписывая код возник вопрос. А в чем смысл использования, например, аннотации OneToMany для связывания двух...

Hibernate, ManyToOne и кривая БД
Суть вопроса такая, есть БД, в которой почти что нет ни одного FK, тем не менее логически связи есть. Так же, как вы уже догадались есть...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
09.05.2013, 22:15
Помогаю со студенческими работами здесь

Hibernate ManyToOne лишние записи
Есть такие сущности. @MappedSuperclass class Base { @Id private String id; } @Entity class A extends Base { ...

JPA: Hibernate
Где-то читал, что реализация JPA от Hibernate это entity-manager. Но там даже нету классов типа javax.persistence ... Нашел такие классы...

Не записывает в базу Spring4+JPA+Hibernate
Пишу проэкт на Spring 4 + Gradle + Hibernate. Пытаюсь добавить в таблицу юзеров пользователя. Вы дает ошибку: Exception encountered...

JPA/Hibernate Дайте совет по проэктированию Entity
Пишу приложение "Система управления рестораном". Столкнулся с проблемой что немогу придумать как правильно организовать заказ. Есть четыре...

JPA/Hibernate MappingException: Foreign key must have same number
Вот описание ошибки. org.hibernate.MappingException: Foreign key (FK_n9nvapt8aqpregmwepb98hjed:questions )) must have same number of...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и источниками (напряжения, ЭДС и тока). Найти токи и напряжения во всех элементах. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru