Okay I have an application that maps Semesters to their courses;
public class Course {
private String courseId;
private String courseName;
private Collection<Semester> semesters = new ArrayList<>();
#OneToMany(targetEntity = Semester.class, mappedBy = "course")
public Collection<Semester> getSemesters() {
return semesters;
}
public void setSemesters(Collection<Semester> semesters) {
this.semesters = semesters;
}
#Id
#Column (name = "COURSE_ID")
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
#Column(name = "COURSE_NAME", nullable = false, unique = true)
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
As you can see the users class is mapped to the Semesters entity using One to Many mapping.
The Semester class is as follows;
#Entity
#Table (name = "SEMESTERS")
public class Semester {
private int semNum;
private Course course;
#ManyToOne
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
#Id
#Column (name = "SEM_NUM")
public int getSemNum() {
return semNum;
}
public void setSemNum(int semNum) {
this.semNum = semNum;
}
}
As you can see I am using mappedBy to map the course directly into the semester table. But the problem is that the field in the semester table comes as course_COURSE_ID.
How can I change this column name to just COURSE_ID ?
You need to use the #JoinColumn annotation.
#ManyToOne
#JoinColumn(name="COURSE_ID")
public Course getCourse() {
//code
}
I would suggest you to read the documentation as this is very well explained in there. If you don't want to read the docs, then be ready for a long and painful journey, as JPA is not a simple technology, and it has a multitude of gotchas.
You can change this via #JoinColumn in the Semester class. This allow to change the default JPA names.
Should look like this:
public class Semester {
#ManyToOne
#JoinColumn(name="COURSE_ID")
public Course getCourse() {
return course;
}
}
Related
I'm having some issues with what I believe is my relational mapping in Hibernate. This is for an recipe keeping application.
Originally, the recipe class had a String ingredients field where all of the ingredients were stored. We realized that this didn't make sense for storing a list of ingredients in a recipe, so I'm in the process of refactoring it to be a list of a new type I created, Ingredient: List<Ingredient> ingredients. The ingredient form field is dynamically created by JS on the front end, and when submitted on a POST request, is transformed into an ArrayList of new Ingredients and then added into the Recipe model.
Whenever it reaches the line where it saves it into the database, I get this error:
Field 'ingredients' doesn't have a default value, which tells me that the field is null. However, when I use the debug tools, it shows me that newRecipe.ingredients is not null, its actually an ArrayList created from the data on the front end.
The Ingredient class looks like such:
#Entity
public class Ingredient extends AbstractEntity{
#ManyToOne(targetEntity = Recipe.class,
fetch = FetchType.LAZY,
cascade = {CascadeType.MERGE, CascadeType.REMOVE})
#NotNull(message = "Please include ingredients")
private Recipe recipe;
#Id
#GeneratedValue
private int id;
private String ingredient;
public Ingredient(String ingredient) {
this.ingredient = ingredient;
}
public String getIngredient() {
return ingredient;
}
public void setIngredient(String ingredient) {
this.ingredient = ingredient;
}
}
The Recipe Class is here:
#Entity
public class Recipe extends AbstractEntity {
private String name;
#OneToMany(mappedBy = "recipe")
#NotNull(message = "Ingredients required")
private List<Ingredient> ingredients = new ArrayList<Ingredient>();
private String directions;
#OneToMany(mappedBy = "recipe")
private List<Instruction> instructions = new ArrayList<Instruction>();
#NotNull(message = "Category required")
private Category category;
private Tag tag;
private String img;
#OneToMany(mappedBy = "recipe", cascade = {CascadeType.MERGE, CascadeType.REMOVE})
#NotNull(message = "User is required")
private List<UserRecipe> users = new ArrayList<>();
public Recipe() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<UserRecipe> getUsers() {
return users;
}
public void setUsers(List<UserRecipe> users) {
this.users = users;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public List<Ingredient> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredient> ingredients) {
this.ingredients = ingredients;
}
public String getDirections() {
return directions;
}
public void setDirections(String directions) {
this.directions = directions;
}
public Tag getTag() {
return tag;
}
public void setTag(Tag tag) {
this.tag = tag;
}
public List<Instruction> getInstructions() {
return instructions;
}
public void setInstructions(List<Instruction> instructions) {
this.instructions = instructions;
}
}
RecipeController is here:
#PostMapping("create")
public String createRecipe(HttpServletRequest request, #ModelAttribute Recipe newRecipe,
#ModelAttribute #Valid String newCategory,
Errors errors, Model model, RedirectAttributes redirectAttrs) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Recipe");
return "recipes/create";
}
String[] ingredients = request.getParameterValues("ingredient");
List<Ingredient> ingredientsList = new ArrayList<Ingredient>();
for (int i = 0; i < ingredients.length; i++) {
Ingredient newIngredient = new Ingredient(ingredients[i]);
ingredientsList.add(newIngredient);
}
newRecipe.setIngredients(ingredientsList);
// THIS PRINTS AN ARRAY OF THE NUMBER OF INGREDIENTS ADDED
System.out.println(ingredientsList.toString());
// HERE IS WHERE MY ERROR HAPPENS
Recipe recipe = recipeRepository.save(newRecipe);
redirectAttrs.addAttribute("recipeId", recipe.getId());
return "redirect:/recipes/display";
}
My thought here is that I'm somehow not mapping the ingredients list correctly to the recipe, but I can't figure this one out and after 3 days of googling and troubleshooting here I am. Any help would be greatly appreciated. Thanks in advance!
This can be a problem of the schema in your database. Did you create your schema manually or are you using auto-ddl? If you created it manually, maybe you are missing a recipe_id column in the Ingredients table. If such join column has a different name, you must override it using #JoinColumn on the Ingredient class like this:
#ManyToOne(targetEntity = Recipe.class,
fetch = FetchType.LAZY,
cascade = {CascadeType.MERGE, CascadeType.REMOVE})
#NotNull(message = "Please include ingredients")
#JoinColumn("the_recipe_id") // **** Here you put the join column name you specified **** //
private Recipe recipe;
EDIT: Also, can you post your AbstractEntity class? The problem could also be related with the lack of key in the Recipe class.
I'm an idiot. The data type was set incorrectly in the database. Creating a new DB solved it.
I'm trying to map 2 entities (Course and Student), I have 2 Java classes and 2 MySQL tables, having a ManyToMany relationship. I created the junction table and java class Enrolment (as I want extra information such as the date of enrolment of a student to a course).
I'm trying to insert data using hibernate in this Enrolments table in the MySQL but I keep getting errors. Here are my POJO classes:
Course class:
#Entity
#Table(name = "course")
public class Course {
private int id;
#Column(name = "chapter_id")
private int chapterId;;
#Column(name = "name")
private String title;
#Column(name = "teacher_user_id")
private int teacherId;
#OneToMany(targetEntity=Enrolment.class, mappedBy="course", fetch=FetchType.LAZY)
// #JoinTable(name = "enrolment",
// joinColumns = #JoinColumn(name = "course_id"),
// inverseJoinColumns = #JoinColumn(name = "student_user_id"))
private List<Enrolment> enrolments = new ArrayList<Enrolment>();
public Course(){}
public Course(int id, int chapterId, String title, int teacherId) {
super();
this.id = id;
this.chapterId = chapterId;
this.title = title;
this.teacherId = teacherId;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getChapterId() {
return chapterId;
}
public void setChapterId(int chapterId) {
this.chapterId = chapterId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
#OneToMany(mappedBy = "course")
public List<Enrolment> getEnrolments() {
return enrolments;
}
public void setEnrolments(List<Enrolment> courses) {
this.enrolments = courses;
}
public void addEnrolment(Enrolment enrolment) {
this.enrolments.add(enrolment);
}
}
Student class (this class is inherited from User parent class, I will attach User Class down below as well. In the database there are different tables as well: User and then Student and Teacher that inherit User parent entity):
#Entity
#Table(name = "student")
#PrimaryKeyJoinColumn(name = "user_id")
#OnDelete(action = OnDeleteAction.CASCADE)
public class Student extends User {
private int grade;
private List<Enrolment> enrolments = new ArrayList<Enrolment>();
public Student(){}
public Student(String fname, String lname, String email, String password, String address, String phone,
int userType, int grade, boolean isAdmin)
{
super(fname, lname, email, password, address, phone, userType, isAdmin);
this.grade=grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void setEnrolments(List<Enrolment> courses) {
this.enrolments = courses;
}
#OneToMany(mappedBy = "student")
public List<Enrolment> getEnrolments() {
return enrolments;
}
public void addCourse(Enrolment course) {
this.enrolments.add(course);
}
public void addEnrolment(Enrolment enrolment) {
this.enrolments.add(enrolment);
}
}
User Class:
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstname;
private String lastname;
private String email;
private String password;
private String address;
private String phone;
#Column(name = "user_type_id")
private int userType;
#Column(name = "is_admin")
private boolean isAdmin;
public User(String fname, String lname, String email, String password, String address, String phone,
int userType, boolean isAdmin) {
//super();
this.firstname = fname;
this.lastname = lname;
this.email = email;
this.password = password;
this.address = address;
this.phone = phone;
this.userType = userType;
this.isAdmin = isAdmin;
}
public User() {}
//getters & setters
And finally this is the Enrolment class:
#Entity
#Table(name = "enrolment")
public class Enrolment {
private int id;
private Student user;
private Course course;
#Column(name = "enrolment_date")
private Date enrolmentDate;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "student_user_id")
public User getUser() {
return user;
}
public void setUser(Student user) {
this.user = user;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "course_id")
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Date getEnrolmentDate() {
return enrolmentDate;
}
public void setEnrolmentDate(Date enrolmentDate) {
this.enrolmentDate = enrolmentDate;
}
So I'm trying to read a course and a student from database and insert the information in this Enrolment table but it gives errors since trying to read a Course. Here is the DAO method:
#SuppressWarnings("deprecation")
#Transactional
public List<Course> getCoursesOfChapter(int chapterId) {
Configuration con = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Course.class);
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Course where chapter_id = :chapterId");
query.setParameter("chapterId",chapterId);
// List list = query.list();
tx.commit();
return (List<Course>) query.list();
It throws the error at the session factory building:
Exception in thread "main" org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: models.Course.enrolments[models.Enrolment]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1255)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:808)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:733)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1696)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1664)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:84)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:474)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at dao.CourseDAO.getCourse(CourseDAO.java:52)
at webapp.Main.main(Main.java:132)
Finally, this is my call:
CourseDAO cdao = new CourseDAO();
Course course = cdao.getCourse(1);
I've tried playing with the annotations, make them ManyToMany instead of ManyToOne. I tried to map the User class instead of Student but still didn't work. I tried to make it without the junction class of Enrolment and just generate it without having an actual class for it but still didn't work (as I had to work with 2 session.save() methods one after the other which also gave some error that I couldn't solve). Probably it's a small thing that I'm missing here but I just can't figure it out, sorry for too long code but I really need to solve it fast. If you read through here, I really thank you!
So my question is: Am I missing something here from these mappings and annotations or I should change the structure of my classes?
Boiling down a problem to the bare minimum greatly helps others help you. Here are simpler versions of your student, course and enrollment classes that can be unit tested easily. The many-to-many association between course and student is separated into two many-to-one associations from Enrollment. Note that the associations are bidirectional and that the many side is mapped by the one side. Student cascades persistence operations to Enrollment, which reflects how schools normally work: students enroll in courses, not the other way around.
Course.java
#Entity
public class Course {
#Id
#GeneratedValue
private Long id;
private String title;
#OneToMany(mappedBy = "course")
private List<Enrollment> enrollments;
Course() {
}
Course(String title) {
this.title = title;
this.enrollments = new ArrayList<>();
}
void add(Enrollment enrollment) {
enrollments.add(enrollment);
}
Long getId() {
return id;
}
List<Enrollment> getEnrollments() {
return enrollments;
}
}
Student.java
#Entity
public class Student {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "student", cascade = ALL, orphanRemoval = true)
private List<Enrollment> enrollments;
Student() {
}
Student(String name) {
this.name = name;
this.enrollments = new ArrayList<>();
}
void enroll(Course course) {
enrollments.add(new Enrollment(course, this));
}
}
Enrollment.java
#Entity
public class Enrollment {
#Id
#GeneratedValue
private Long id;
#ManyToOne
private Course course;
#ManyToOne
private Student student;
Enrollment() {
}
Enrollment(Course course, Student student) {
this.course = course;
this.student = student;
course.add(this);
}
}
The test case below checks that the entities are mapped and associated correctly. You can run it with Spring Boot.
SchoolTest.java
#RunWith(SpringRunner.class)
#SpringBootTest
#Transactional
public class SchoolTest {
#Autowired
private CourseRepository courseRepository;
#Autowired
private StudentRepository studentRepository;
#Test
public void run() {
Course course = courseRepository.save(new Course("cs_101"));
int studentCount = 3;
for (int i = 1; i <= studentCount; i++) {
Student student = new Student("student_" + i);
student.enroll(course);
studentRepository.save(student);
}
// push changes to the database and clear the existing entities
// to make the subsequent operations load from the database
entityManager.flush();
entityManager.clear();
Optional<Course> savedCourse = courseRepository.findById(course.getId());
assertTrue(savedCourse.isPresent());
assertEquals(studentCount, savedCourse.get().getEnrollments().size());
}
}
As the warning said, your Enrollment is not registered in Hibernate. If you really don't need it. Please use transient annotation. read more here
SOLVED
But the real problem wasn't hibernate, it was mainly me and second Netbeans.
I was making a post, and saving my data. But I was making a duplicate post in js, and Netbeans won't fire breakpoints twice (and I don't really know why). So, for me, it was making one post and just one insert. But no, two posts, and two inserts.
Sorry for losing your time :/
I'm new to Hibernate, so I'm having some problems, maybe it's just a silly one, I don't really know.
I'm trying to insert an object to database with a #ManyToOne relationship, but Hibernate is duplicating it when I persist and commit the transaction. This is my code.
User Post Class
#Entity
#Table(name = "USERPOST", schema = "ADMIN1")
public class UserPost implements java.io.Serializable {
private int iduserpost;
private String detail;
private User user;
public UserPost() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "IDUSERPOST", unique = true, nullable = false)
public int getIduserpost() {
return this.iduserpost;
}
public void setIduserpost(int iduserpost) {
this.iduserpost = iduserpost;
}
#Column(name = "DETAIL", nullable = false)
public String getDetail() {
return this.detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
#ManyToOne
#JoinColumn(name = "IDUSER")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Class
#Entity
#Table(name = "USER", schema = "ADMIN1")
public class User implements java.io.Serializable {
private int iduser;
private String name;
private String email;
private Set<UserPost> posts;
public User() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "IDUSER", unique = true, nullable = false)
public int getIduser() {
return this.iduser;
}
public void setIduser(int iduser) {
this.iduser = iduser;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "EMAIL", nullable = false)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#OneToMany(mappedBy = "user")
public Set<UserPost> getPosts() {
return posts;
}
public void setPosts(Set<UserPost> posts) {
this.posts = posts;
}
}
Insert Method on Manager
public void Insert(Object data) {
Session session = null;
try {
session = hibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.persist(data);
session.getTransaction().commit();
} catch (Exception e) {
System.err.println(e.getMessage());
throw e;
} finally {
if (session.isOpen()) {
session.close();
}
}
}
Insert on Servlet
FeedManager manager = new FeedManager();
UserPost post = new UserPost();
post.setDetail(text);
User usrPesist = (User) manager.GetById(User.class, idUser);
post.setUser(usrPesist);
manager.Insert(post);
The result I'm getting is TWO UserPosts being inserted to database, when what I want is just one.
Is there something wrong?
Since you have defined as private Set<UserPost> posts; in User Class,
implement equals and hashcode methods in UserPost class , in that way you ensure that since it is a Set it wont add duplicates
But this is not a optimal way though.
I think this is problem with you id generation strategy in your user class. Just try by setting id manually in user class object it will work.
Try changing your code with this :
#org.hibernate.annotations.Cascade( {org.hibernate.annotations.CascadeType.SAVE_UPDATE})
#OneToMany(mappedBy = "user")
#JoinColumn(name = "IDUSER")
public Set<UserPost> getPosts() {
return posts;
}
I'm trying to create manytomany realation between Student and Teaching Course using Composite Primary key:
my classes:
#Entity
#Table(name="Student_mtm_cId")
public class Student {
private String id;
private Set<StudentTClass> teachingClasses = new HashSet<StudentTClass>();
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.student")
public Set<StudentTClass> getTeachingClasses() {
return teachingClasses;
}
public void setTeachingClasses(Set<StudentTClass> teachingClasses) {
this.teachingClasses = teachingClasses;
}
public void addStudentToClass(TeachingClass teachingClass){
StudentTClass studentTClass = new StudentTClass();
studentTClass.setStudent(this);
studentTClass.setTeachingClass(teachingClass);
teachingClasses.add(studentTClass);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
#Column(name = "student_id", nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//all other setters and getters and isequal/hashCode omitted.
}
TeachingClass:
#Entity
#Table(name="TechingClass_MTM")
public class TeachingClass {
private String id;
private String name;
private String description;
private Set<StudentTClass> teachingClasses = new HashSet<StudentTClass>();
public TeachingClass(){}
public TeachingClass(String name, String description) {
super();
this.name = name;
this.description = description;
}
public void addStudentToClass(Student student){
StudentTClass studentTClass = new StudentTClass();
studentTClass.setStudent(student);
studentTClass.setTeachingClass(this);
teachingClasses.add(studentTClass);
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.teachingClass")
public Set<StudentTClass> getTeachingClasses() {
return teachingClasses;
}
public void setTeachingClasses(Set<StudentTClass> teachingClasses) {
this.teachingClasses = teachingClasses;
}
public void setDescription(String description) {
this.description = description;
}
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
#Column(name = "teachingClass_id", nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Collection Objects:
#Entity
#Table(name = "student_TClass_MTM")
#AssociationOverrides({
#AssociationOverride(name = "pk.student", joinColumns = #JoinColumn(name = "student_id")),
#AssociationOverride(name = "pk.teachingClass", joinColumns = #JoinColumn(name = "teachingClass_id"))
})
public class StudentTClass {
#EmbeddedId
private StudentTClassPK pk = new StudentTClassPK();
public StudentTClassPK getPk() {
return pk;
}
public void setPk(StudentTClassPK pk) {
this.pk = pk;
}
public StudentTClass() {}
#Transient
public Student getStudent(){
return this.pk.getStudent();
}
#Transient
public TeachingClass getTeachingClass(){
return this.pk.getTeachingClass();
}
public void setStudent(Student student){
this.pk.setStudent(student);
}
public void setTeachingClass(TeachingClass teachingClass){
this.pk.setTeachingClass(teachingClass);
}
}
Now The primary Key:
#Embeddable
public class StudentTClassPK implements Serializable{
private static final long serialVersionUID = -7261887879839337877L;
private Student student;
private TeachingClass teachingClass;
#ManyToOne
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#ManyToOne
public TeachingClass getTeachingClass() {
return teachingClass;
}
public void setTeachingClass(TeachingClass teachingClass) {
this.teachingClass = teachingClass;
}
public StudentTClassPK(Student student, TeachingClass teachingClass) {
this.student = student;
this.teachingClass = teachingClass;
}
public StudentTClassPK() {}
}
When I'm trying to Persist Student I got the following error:
Caused by: org.hibernate.MappingException: Could not determine type for: com.vanilla.objects.Student, at table: student_TClass_MTM, for columns: [org.hibernate.mapping.Column(student)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:306)
at org.hibernate.tuple.PropertyFactory.buildStandardProperty(PropertyFactory.java:143)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:68)
at org.hibernate.mapping.Component.buildType(Component.java:184)
at org.hibernate.mapping.Component.getType(Component.java:177)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:290)
at org.hibernate.mapping.RootClass.validate(RootClass.java:236)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:855)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:774)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 51 more
What am I doing wrong?
I solved this issue. I mapped Getter instead of field.
public class StudentTClass {
//#EmbeddedId
private StudentTClassPK pk = new StudentTClassPK();
#EmbeddedId
public StudentTClassPK getPk() {
return pk;
}
If you can, I'd seriously suggest removing the composite keys. Worth with simple primary keys can both make a lot of problems go away and simplify your code. I have used composite keys in a database in the past because I had no ability to modify the db. Unfortunately I don't have the code. But I do remember it took some work to get it all working correctly. Sorry, can't help more.
i need some help for my class...
package com.it.ese.orbit.entity;
import javax.persistence.*;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Shahriar Newaz
* Date: 07/03/11
* Time: 10.07
*/
#Entity
#Inheritance(strategy =InheritanceType.JOINED)
public class OrbitObject {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="id",nullable = false)
private Long id;
#Column(name="Scenario",nullable = false)
private String scenario; // not sure about how to map scenario
#Column(name="code",nullable = true)
private String code;
#Column(name="name",nullable = true)
private String name;
#OneToOne(cascade=CascadeType.ALL)
private Bia bia;
#OneToOne(cascade=CascadeType.ALL)
public Impatti impatti;
#Column(name="parent",nullable = true)
#OneToMany(cascade=CascadeType.ALL)
private OrbitObject OrbitObject;
public Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScenario() {
return scenario;
}
public void setScenario(String scenario) {
this.scenario = scenario;
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
// LOG
#Override
public String toString(){
return "com.it.ese.orbit.models.OrbitObject["
+ " - name="+name + " - scenario="+scenario +" - id= "+id+"]";
}
}
But i get thi error...
Caused by: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: com.it.ese.orbit.entity.OrbitObject.OrbitObject
I wish i create an OrbitObject field as like an object of the same class...
Help please!
You either do
#Column(name="parent",nullable = true)
#ManyToOne(cascade=CascadeType.ALL)
private OrbitObject OrbitObject;
Or
#Column(name="parent",nullable = true)
#OneToMany(cascade=CascadeType.ALL)
private Set<OrbitObject> OrbitObject;
The first case implies this entity will be the owning side, namely, it will have the foreign key.
OneToMany means that OrbitObject has many OrbitObject children, which is not true because the OrbitObject property is not a collection.
You must convert it to a ManyToOne
you can use #OneToMany referring to a collection of elements, for example
#OneToMany
List<OrbitObject> orbitList;