Bridge table primary as foreign key in another table (JPA) - database

I'm designing a student enrollment database
Student-Table
student_id (pk)
//other attributes
Course-Table
course_id (pk)
//other attributes
Student_course-Table
student_course_id(pk)
course_id (fk)
student_id (fk)
Lectrue-Table
lecture_id(pk)
student_course_id(fk - > student_course table)
// other attributes
Basically I want to store which student is enrolled to which course and has attend how many lectures for that particular course.
Q1 ) Is this design correct? Should I use primary key of Bridge table as foreign key in another table.
Q2 ) I did manyToMany mapping between student <-> course and oneToMany between student_course <-> lecture and got the following error :
org.hibernate.MappingException: Foreign key must have same number of columns as the referenced primary key
Any idea how to proceed?
//UPDATE Entity class
#Entity
#Table(name = "STUDENT")
public class Student implements Serializable {
#Id
#Column(name = "STUDENT_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToMany(mappedBy = "students" ,cascade = CascadeType.ALL)
#MapKey(name = "courseName")
private Map<String, Course> courses;
}
#Entity
#Table(name = "COURSE", uniqueConstraints = #UniqueConstraint(columnNames = {"COURSE_NAME"}))
public class Course implements Serializable {
#Id
#Column(name = "COURSE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "STUDENT_COURSE", joinColumns = {
#JoinColumn(name = "COURSE_ID") }, inverseJoinColumns = {
#JoinColumn(name = "STUDENT_ID") })
private Set<Student> students;
#Column(name = "COURSE_NAME")
private String courseName;
}
#Entity
#Table(name = "LECTURE")
public class Lecture {
#Id
#Column(name = "LECTURE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "STUDENT_COURSE_ID")
private StudentCourse studentCourse;
}
#Entity
#Table(name = "STUDENT_COURSE")
public class StudentCourse {
#Id
#Column(name = "STUDENT_COURSE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "STUDENT_ID")
private Long studentId;
#Column(name = "COURSE_ID")
private Long courseId;
#OneToMany(mappedBy = "studentCourse")
private Set<Lecture> lectures = new HashSet<Lecture>();
}

Related

Spring DataJPA not saving 3rd tabledata to the database

I have no problem with saving my entities to the database. However when I try to insert values into my 3rd many-to-many table, it simply doesn't do anything.
Here is my student entity;
#Table(name = "student", schema = "school")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long studentId;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "student_classroom", schema = "school")
private Collection<Classroom> classroom = new ArrayList<>();
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinTable(name = "student_teacher",
joinColumns = {
#JoinColumn(name = "student_id", referencedColumnName = "studentId",
nullable = false, updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "teacher_id", referencedColumnName = "teacherId",
nullable = false, updatable = false)})
private Set<Teacher> teachers = new HashSet<>();
The teacher entity.
#Entity
#Table(name = "teacher", schema = "school")
public class Teacher {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long teacherId;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "teacher_classroom", schema = "school")
private Collection<Classroom> classroom = new ArrayList<>();
#ManyToMany(mappedBy = "teachers", fetch = FetchType.LAZY)
private Set<Student> students = new HashSet<>();
Here is my service method.
public void addTeacherToStudent(long teacherId, long studentId) {
Optional<Teacher> teacher = teacherRepository.findById(teacherId);
Optional<Student> student = studentRepository.findById(studentId);
student.get().getTeachers().add(teacher.get());
teacher.get().getStudents().add(student.get());
}
It has no problem saving the teachers and students in the sets in memory, however it doesn't reach the database. I have tried every annotation, didn't work.
Try adding this in Teacher entity
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(
name = "student_teacher",
joinColumns = #JoinColumn(name = "teacher_id"),
inverseJoinColumns = #JoinColumn(name = "student_id")
)
private Set<Student> students = new HashSet<>();

JPQL with Group by clause in SQL Server database not working

I am new to SQL Server database. The below JPQL query is not getting executed and not throwing any errors. Just my application hanging over at this query. This code is working fine with MySQL database, but not with SQL Server(2019) database.
#Query(value = "SELECT R.riskType, count(distinct V.bname) FROM RiskViolation V JOIN V.job J JOIN V.risk R WHERE J.id = ?1 GROUP BY R.riskType ")
public List<Object[]> sodUserByRiskType(Long jobId);
But when I run the below converted sql query directly in the SQL Server database, it is working fine.
select count(distinct riskviolat0_.bname) as col_1_0_, risklog2_.risk_type as col_0_0_ from risk_violation riskviolat0_ inner join analysis_job analysisjo1_ on riskviolat0_.job_id=analysisjo1_.id inner join risk_log risklog2_ on riskviolat0_.risk_id=risklog2_.id where analysisjo1_.id=? group by risklog2_.risk_type;
Here are the Java entity classes which are used in JPQL query:
RiskViolation.java
#Entity
#Table(name = "risk_violation")
public class RiskViolation {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "job_id")
private AnalysisJob job;
private String bname;
private String riskName;
private String violations;
#Column(name = "violated", columnDefinition = "BIT", length = 1)
private boolean violated;
#Column(name = "simulation", columnDefinition = "BIT", length = 1)
private boolean simulation;
#Column(name = "mitigation_name")
private String mitigationName;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "risk_id")
private RiskLog risk;
#JsonIgnore
#OneToMany(mappedBy = "riskViolation", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<RuleViolation> ruleViolations;
}
AnalysisJob.java
#Entity
#Table(name = "analysis_job")
public class AnalysisJob {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "profile_name")
private String profileName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "profile_id")
#OnDelete(action = OnDeleteAction.CASCADE)
private AnalysisProfileLog profileLog;
#Column(name = "description")
private String description;
#Column(name = "status")
private String status;
#Column(name = "started_on")
private Date startedOn;
#Column(name = "completed_on")
private Date completedOn;
#Column(name = "completion_message")
private String completionMessage;
#Column(name = "percent_completed")
private float percentCompleted;
#Column(name = "run_by")
private String runBy;
#Column(name = "removed", columnDefinition = "BIT", length = 1)
private boolean removed;
#OneToMany(mappedBy = "job", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
private List<JobResultData> resultData;
#Column(name = "pos_analysis", columnDefinition = "BIT", length = 1)
private boolean posAnalysis;
#Column(name = "submitted", columnDefinition = "BIT", length = 1)
private boolean submitted;
#Column(name = "position_id")
private String positionId;
}
RiskLog.java
#Entity
#Table(name = "risk_log")
public class RiskLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long jobId;
private String name;
private String riskDescription;
private String riskCondition;
private String businessProcess;
#Column(name = "business_sub_process")
private String subProc;
private String riskType;
#JsonIgnore
#OneToMany(mappedBy = "riskLog", cascade = CascadeType.ALL)
protected List<RuleLog> rules;
}
Do I need to make any changes to the query and entity classes to make it work?
Here is Query Plan URL
Estimated Execution Plan
Actual Execution Plan
Query Plan with Actual Rows
It worked after avoiding facade class between Java class (where my business logic resides) and JPA repository( use to execute JPQL queries). Directly invoked JPA repository method from Java class. Not sure why it did not work with facade class with SQL Server, but same worked with MySQL database.

Hibernate: ManyToOne generating field raw(255)

I recently upgraded from hibernate-core 4.1.7 to 5.0.9 and Have problem with this code:
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name = "FK_AAA", foreignKey = #ForeignKey(name = "CS_BBB"))
#org.hibernate.annotations.Index(name = "IDX_CCC", columnNames = "FK_DDD")
private ImportData importData;
This generate correct foreign columns pointing to the defining class, but also generating a column on the same class:
IMPORTDATA RAW(255)
Why is this raw(255) column generated ? I think it was not generated with Hibernate-core 4.1.7
any idea ?
Update 1: here is longer code fragments:
#MappedSuperclass
#Access(AccessType.PROPERTY)
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public abstract Long getId();
}
#Entity
#Table(name = "IMPORT_DATA", uniqueConstraints = {
#UniqueConstraint(name = "UC_IMP_BID", columnNames = {"BUSINESS_ID"})
}, indexes = {
#Index(name = "IDX_IMP_DGXML_ID", columnList = "FK_DGXML_ID"),
#Index(name = "IDX_IMP_IMPXML_ID", columnList = "FK_IMPXML_ID")
})
public class ImportData extends BaseEntity {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() { return id; }
// ...
}
#Entity(name = "MUTATION")
#Table(name = "MUTATION")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING)
#SequenceGenerator(name = "mutationsSeq", sequenceName = "MUTATIONS_SEQUENCE", allocationSize = 1)
public abstract class Mutation extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "mutationsSeq")
private Long id;
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name = "FK_IMP_ID", foreignKey = #ForeignKey(name = "CS_MUT_IMP_ID"))
#org.hibernate.annotations.Index(name = "IDX_MUT_IMP_ID", columnNames = "FK_IMP_ID")
protected ImportData importData;
}
#Entity(name="XXX")
#DiscriminatorValue("XXX_DISC")
public class XXX extends Mutation {
// ...
}
I found an answer on Mapping composite key with Hibernate produces a raw field in Oracle:
I was mixing annotations on fields and methods. I also had #Id on an abstract superclass, and a redefinition on a derived class.
Fixing theses two elements, cleaning DB and regenerating in "create" ddl mode proved that the fix was no longer generating RAW field type.
Thanks for all your helps!

Hibernate cascade parent child when using sql server spatial dialect

I am using spring boot data jpa with SQLServer and spatial dialect as below:
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.sqlserver.SqlServer2008SpatialDialect
Parent Class:
#Entity
#Table(name = "users", schema = "dbo")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
#JoinTable(name = "users_roles",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles = new ArrayList<>();
}
Child Class:
#Entity
#Table(name = "roles", schema = "dbo")
public class Role {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#ManyToMany(mappedBy="roles", cascade = {CascadeType.ALL})
private Collection<User> users = new ArrayList<>();
}
on saving user:
u.setRoles(roles);
userRepository.save(u);
but alyways get user_id equals zero on table users_roles
please help
Note that SpatialDialect is needed to manage spatial data on other entities.

how to use hibernate annotations OnetoOne in springMvc?

I'm working with spring MVC``Spring security hibernate
I've created 2 tables in the database , this the schema:
create table user(
id int(10),
name VARCHAR(30) NOT NULL,
address VARCHAR(30) NOT NULL,
PRIMARY KEY (id)
);
create table compte(
id int(10),
login VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES user( id)
);
I'm developing a web application for users managements, the administrator add user's informations and submit (data from the first form is inserted into the userdatabase) and then in an other jsp he adds the authentication data for this user and submit ( here data is inserted into the second database compte )
the form in the jsp page that inserts into user's table is done correctly when it's not joined to any other table .
But when I tried to use hibernate annotations in my application and join the two tables user and compte I have errors :
Caused by: org.hibernate.AnnotationException: Unknown mappedBy in: com.package.domain.User.compte, referenced property unknown: com.package.domain.Compte.User
user.java :
#Entity
#Table(name = "user")
public class User {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="address")
private String address;
#OneToOne(mappedBy="User", cascade=CascadeType.ALL)
private Compte compte;
//getters and setters
compte.java :
#Entity
#Table(name = "COMPTE")
public class Compte {
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
#OneToOne
#PrimaryKeyJoinColumn
private User user;
//getters and setters
I don't know how should I insert comptedata into the second table ? how it will recognize that the login and the password correspond to the user's id just inserted.
PS : i've created 2 tables in the database to use the second for authentication in spring security if my database design is incorrect please tell me :)
Firstly, you need to specify not a class name (User), but a property name (user) in the mappedBy
#OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Compte compte;
In my opinion It will be better to associate Compte to the User by an additional foreign key and I would like to have login and password in the User table.
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue
#Column(name = "f_id")
private int id;
#Column(name = "f_login")
private String login;
#Column(name = "f_password")
private String password;
#OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Compte compte;
}
#Entity
#Table(name = "comptes")
public class Compte {
#Id
#GeneratedValue
#Column(name = "f_id")
private int id;
#OneToOne
#JoinColumn(name = "fk_user")
private User user;
#Column(name = "f_name")
private String name;
}

Resources