为什么在 Hibernate 的 @OneToMany 注释的一侧需要一个辅助方法?

huangapple go评论69阅读模式
英文:

Why do we need a helper method inside @OneToMany annotated side in hibernate?

问题

Instructor类中的addCourse()方法有什么必要性,是否可以不创建这个方法?

addCourse()方法的目的是为了维护Instructor和Course之间的关系,特别是在双向一对多关系中。这个方法允许你方便地将一个课程关联到一个特定的讲师(Instructor)对象,并且确保关系的一致性。通过这个方法,你可以:

  1. 向Instructor对象中的courses列表添加一个Course对象。
  2. 设置Course对象的instructor属性为当前的Instructor对象,建立了从课程到讲师的关联。

如果不使用addCourse()方法,你需要手动执行这两个步骤,这可能会导致代码重复和错误。因此,这个方法的存在有助于代码的可维护性和可读性,确保了关系的正确建立和维护。所以,一般来说,建议保留这个方法。

英文:

Here I have two entity classes called Course and Instructor which follows bi directional one to many relationship.Source code is given below.I need to know what's the need of the addCourse() method in the Instructor class and can't we create the class without it?

Source code.

Instructor class

@Entity
@Table(name="Instructor")

public class Instructor {
	

	@Id
	@GeneratedValue(strategy =GenerationType.IDENTITY )
	@Column(name="id")
	private int id;

	@Column(name="first_name")
	private String firtName;
	
	@Column(name="last_name")
	private String lastName;
	
	@Column(name="email")
	private String email;
	
	
	
	@OneToMany(mappedBy ="instructor" ,cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH}) 
	private List<Course> courses;


    //Getters and Setters + Constructors + toString() method

	
	public void addCourse(Course tempCourse) {//Helper method
		if(courses == null) {
			courses = new ArrayList<>();
		}
		courses.add(tempCourse);
		tempCourse.setInstructor(this);
	}

}

Course class

@Entity
@Table(name="course")
public class Course {
	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	
	@Column(name="title")
	private String title;
	
    @ManyToOne(cascade ={CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH} )
	@JoinColumn(name="instructor_id")
	private Instructor instructor;
	
	//Getters and Setters + Constructors + toString() method	

	
}

答案1

得分: 1

Vlad Mihalcea表示,双方(父对象和子对象)应保持同步,以确保不破坏领域模型的一致性并避免状态转换错误。链接:https://vladmihalcea.com/jpa-hibernate-synchronize-bidirectional-entity-associations/

英文:

Vlad Mihalcea says both sides (parent and child) should be in sync so not breaking Domain Model consistency and avoiding state transition bugs:
https://vladmihalcea.com/jpa-hibernate-synchronize-bidirectional-entity-associations/

答案2

得分: 0

以下是翻译好的部分:

"没有必要有这个方法。实际上,这是一个方便的方法,允许快速将课程添加到属于教师对象的List<Course>中。

这个方法的作用是在列表不存在的情况下初始化列表,将Course对象设置为课程列表,同时将传入的Course对象设置为Instructor对象。

您完全可以使用以下代码替换这个方法,并仍然实现相同的结果:

public class Instructor {

// 其他内容

Set<Course> courses = new HashSet<>();
// 标准的getter和setter方法

}

然后,在所需的调用点,您可以简单地执行以下操作:

Course course = new Course();
course.setTitle("My Title");
course.setIntructor(instructor);

instructor.getCourses().add(course);

以上代码本质上就是您的方法所做的事情,唯一的区别是不初始化列表对象。"

英文:

There is no need to have this method. What this is instead is a convenience method that allows for quickly adding a course to the List<Course> of courses belonging to an instructor object.

What this does is to initialize the list if not already present, set the Course object to the list of courses as well as set the Instructor object to the passed in Course object.

You could very well replace this method with the following code and still achieve the same results:

public class Instructor {

// misc stuff here

Set<Course> courses = new HashSet<>();
//standard getters/setters

}

And then the desired calling point you could simply do this:

Course course = new Course();
course.setTitle("My Title");
course.setIntructor(instructor);

instructor.getCourses().add(course);

What the above do is essentially what your method does with the exception of not initializing the list object.

答案3

得分: 0

这个方法只是检查列表是否为空,如果不为空,就创建它,你可以不使用它:

@OneToMany(mappedBy = "instructor",
        cascade = {CascadeType.DETACH,
                   CascadeType.MERGE,
                   CascadeType.PERSIST,
                   CascadeType.REFRESH})
private List<Course> courses = new ArrayList<>();

它的另一个作用是添加对课程的引用,确保关系是双向的,课程引用讲师,反之亦然。

你可以将这部分代码移除,并在一个服务方法中进行这些检查。

回答你的问题,你可以创建一个没有这部分代码的相同类,但你将不得不在其他地方执行这些操作,这种设计可以工作,但它是不良设计,addCourse 应该是一个服务方法,在那里放置它会使你的 POJO 实体具有逻辑和控制,但方法的逻辑是正确的。

英文:

The method just checks if the list is null and creates it if it's not there you can leave this out using:

@OneToMany(mappedBy =&quot;instructor&quot; ,
cascade= {CascadeType.DETACH,
CascadeType.MERGE,
CascadeType.PERSIST,
CascadeType.REFRESH}) 
    private List&lt;Course&gt; courses = new ArrayList&lt;&gt;();

The other thing that it does is add reference to the course that makes sure the relation is bidirectional where the course reference the instructor and vise versa.

you can take this out and make these checks in a service method.

to answer your question, you can make the same class without it, but you'll have to do those things somewhere else, this design works, but it's bad design, addCourse should be a service method, putting it there makes you're pojo entity somthing that has logic and control, but the logic of the method is right.

huangapple
  • 本文由 发表于 2020年8月6日 05:01:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63273433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定