Hibernate add an entity with foreign key using REST
up vote
0
down vote
favorite
First of all, I haven't written any SQL statements to create a table. I try to use Hibernate/jpa only without writing SQL.
My relation is in the following: A user can have many task, a task only has one user.
I created my models as this:
User Table:
@Entity
@Table(name="T_USER")
@EntityListeners(AuditingEntityListener.class)
public class User
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "uid")
private Long uid;
...
Task Table:
@Entity
@Table(name = "T_TASK")
@EntityListeners(AuditingEntityListener.class)
public class TASK
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long tid;
@ManyToOne
@JoinColumn(name ="oid")
private User owner;
public User getOwner()
return owner;
public void setOwner(User owner)
this.owner = owner;
...
The relation is task's ownerid(oid) is user's uid.
To save a user to my database, I'm using postman with the following parameters:
"username": "firstuser",
"email": "firstuser@email.com"
To save a task to my database I'm using this:
"description": "some description",
"oid": "12" // I also can state username of the user rather than ID
However, as I execute save a task, the oid of task is NULL. In data access objects, I have:
@PostMapping("/save")
public QR createTask(@Valid @RequestBody Task task)
return taskDAO.save(task);
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid.
2-Should I create a table first with SQL using
Create table task(
tid BIGINT,
description VARCHAR(255),
oid BIGINT,
PRIMARY KEY(tid), FOREIGN KEY(oid) REFERENCES (user.uid))
3-Should I change my save method in TaskDAO?
public Task save(Task task)
return taskRepository.save(task);
4- Should I change my controller method(createTask method using RESTcall)
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
I hope I explained my problem. Any feedback will be appreciated.
java hibernate rest postman dao
add a comment |
up vote
0
down vote
favorite
First of all, I haven't written any SQL statements to create a table. I try to use Hibernate/jpa only without writing SQL.
My relation is in the following: A user can have many task, a task only has one user.
I created my models as this:
User Table:
@Entity
@Table(name="T_USER")
@EntityListeners(AuditingEntityListener.class)
public class User
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "uid")
private Long uid;
...
Task Table:
@Entity
@Table(name = "T_TASK")
@EntityListeners(AuditingEntityListener.class)
public class TASK
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long tid;
@ManyToOne
@JoinColumn(name ="oid")
private User owner;
public User getOwner()
return owner;
public void setOwner(User owner)
this.owner = owner;
...
The relation is task's ownerid(oid) is user's uid.
To save a user to my database, I'm using postman with the following parameters:
"username": "firstuser",
"email": "firstuser@email.com"
To save a task to my database I'm using this:
"description": "some description",
"oid": "12" // I also can state username of the user rather than ID
However, as I execute save a task, the oid of task is NULL. In data access objects, I have:
@PostMapping("/save")
public QR createTask(@Valid @RequestBody Task task)
return taskDAO.save(task);
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid.
2-Should I create a table first with SQL using
Create table task(
tid BIGINT,
description VARCHAR(255),
oid BIGINT,
PRIMARY KEY(tid), FOREIGN KEY(oid) REFERENCES (user.uid))
3-Should I change my save method in TaskDAO?
public Task save(Task task)
return taskRepository.save(task);
4- Should I change my controller method(createTask method using RESTcall)
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
I hope I explained my problem. Any feedback will be appreciated.
java hibernate rest postman dao
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
First of all, I haven't written any SQL statements to create a table. I try to use Hibernate/jpa only without writing SQL.
My relation is in the following: A user can have many task, a task only has one user.
I created my models as this:
User Table:
@Entity
@Table(name="T_USER")
@EntityListeners(AuditingEntityListener.class)
public class User
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "uid")
private Long uid;
...
Task Table:
@Entity
@Table(name = "T_TASK")
@EntityListeners(AuditingEntityListener.class)
public class TASK
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long tid;
@ManyToOne
@JoinColumn(name ="oid")
private User owner;
public User getOwner()
return owner;
public void setOwner(User owner)
this.owner = owner;
...
The relation is task's ownerid(oid) is user's uid.
To save a user to my database, I'm using postman with the following parameters:
"username": "firstuser",
"email": "firstuser@email.com"
To save a task to my database I'm using this:
"description": "some description",
"oid": "12" // I also can state username of the user rather than ID
However, as I execute save a task, the oid of task is NULL. In data access objects, I have:
@PostMapping("/save")
public QR createTask(@Valid @RequestBody Task task)
return taskDAO.save(task);
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid.
2-Should I create a table first with SQL using
Create table task(
tid BIGINT,
description VARCHAR(255),
oid BIGINT,
PRIMARY KEY(tid), FOREIGN KEY(oid) REFERENCES (user.uid))
3-Should I change my save method in TaskDAO?
public Task save(Task task)
return taskRepository.save(task);
4- Should I change my controller method(createTask method using RESTcall)
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
I hope I explained my problem. Any feedback will be appreciated.
java hibernate rest postman dao
First of all, I haven't written any SQL statements to create a table. I try to use Hibernate/jpa only without writing SQL.
My relation is in the following: A user can have many task, a task only has one user.
I created my models as this:
User Table:
@Entity
@Table(name="T_USER")
@EntityListeners(AuditingEntityListener.class)
public class User
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "uid")
private Long uid;
...
Task Table:
@Entity
@Table(name = "T_TASK")
@EntityListeners(AuditingEntityListener.class)
public class TASK
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long tid;
@ManyToOne
@JoinColumn(name ="oid")
private User owner;
public User getOwner()
return owner;
public void setOwner(User owner)
this.owner = owner;
...
The relation is task's ownerid(oid) is user's uid.
To save a user to my database, I'm using postman with the following parameters:
"username": "firstuser",
"email": "firstuser@email.com"
To save a task to my database I'm using this:
"description": "some description",
"oid": "12" // I also can state username of the user rather than ID
However, as I execute save a task, the oid of task is NULL. In data access objects, I have:
@PostMapping("/save")
public QR createTask(@Valid @RequestBody Task task)
return taskDAO.save(task);
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid.
2-Should I create a table first with SQL using
Create table task(
tid BIGINT,
description VARCHAR(255),
oid BIGINT,
PRIMARY KEY(tid), FOREIGN KEY(oid) REFERENCES (user.uid))
3-Should I change my save method in TaskDAO?
public Task save(Task task)
return taskRepository.save(task);
4- Should I change my controller method(createTask method using RESTcall)
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
I hope I explained my problem. Any feedback will be appreciated.
java hibernate rest postman dao
java hibernate rest postman dao
asked Nov 10 at 8:27
i807055
1
1
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
up vote
0
down vote
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid
First of all, I would make sure that the owner is being persisted in the db, just to be sure that you have a value to be referencing
2-Should I create a table first with SQL using
Since you're using ORM, writing an SQL query would defeat the purpose of that, you could, but it's not all that necessary, since the relationships are specified already
3-Should I change my save method in TaskDAO?
4- Should I change my controller method(createTask method using RESTcall)
I think it would be best to change your createTask method, you could include the user's id as a pathvariable or a queryparameter and in that method you find the user using their id and set the user field in the task before passing it to the dto to save the value.
The reason the oid is null is because you do not have such a field in there.
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
In your task repository, you can create a method like
Collection<Task> findAllTasksByOwnerId(Long id);
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
You can specify the cascade type where you have specified the relationship between the task and the user
You can check this link for a simple tutorial on how to cascade in spring
add a comment |
up vote
0
down vote
The oid
is null because there is no such field in Task
. I think you are mixing two concepts here. The first one is the data transfer object that represents your REST data structure. This one should have an oid field. The second one is the persisting entity. This one you have, it's the Task
class.
I would implement a TaskDTO, use Hibernate's session to load the User
by its id, then build a Task
from the User
and the other fields from TaskDTO
, then save the Task like you do.
Regarding your other questions
2 - With a create
or update
value for hibernate.hbm2ddl.auto
, Hibernate can generate or update the tables when you start the application.
5 - You could have this interface
@GetMapping("/user/id")
public List<TaskDTO> getTasks(@PathVariable Long id)
Then I think you can't escape coding a criteria query of some sort.
6 - This is done with configuring the relation with cascade = CascadeType.ALL
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
|
show 5 more comments
up vote
0
down vote
The hibernate builds table and foreign keys automatically.Complex queries we can write in repo/controller in hibernate syntax.
With Crud repository we can delete , create update and read data easily.
for example we have student to course one to many relation.
@OneToMany
@JoinColumn(name = "studentId", referencedColumnName = "studentId", insertable = false, updatable = false)
private List<StudentCourses> studentCourses;
in StudentController I will write
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/registerStudentCourse", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public StudentCourses registerStudentCourse(@RequestBody StudentCourses studentCourse)
if (studentCourse != null)
studentCourse.setLastupdated(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
studentCourse = studentCourseRepository.save(studentCourse);
return studentCourse;
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/findStudentCourses", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public List<StudentCourses> findStudentCourses(@RequestBody String studentId)
List<StudentCourses> courses = new ArrayList<>();
JSONObject requestedJSONObject;
try
requestedJSONObject = new JSONObject(studentId);
String student = requestedJSONObject.getString("studentId");
courses =
studentCourseRepository.findCoursesByStudent(Long.parseLong(student));
catch (JSONException e)
// TODO Auto-generated catch block
return courses;
add a comment |
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid
First of all, I would make sure that the owner is being persisted in the db, just to be sure that you have a value to be referencing
2-Should I create a table first with SQL using
Since you're using ORM, writing an SQL query would defeat the purpose of that, you could, but it's not all that necessary, since the relationships are specified already
3-Should I change my save method in TaskDAO?
4- Should I change my controller method(createTask method using RESTcall)
I think it would be best to change your createTask method, you could include the user's id as a pathvariable or a queryparameter and in that method you find the user using their id and set the user field in the task before passing it to the dto to save the value.
The reason the oid is null is because you do not have such a field in there.
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
In your task repository, you can create a method like
Collection<Task> findAllTasksByOwnerId(Long id);
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
You can specify the cascade type where you have specified the relationship between the task and the user
You can check this link for a simple tutorial on how to cascade in spring
add a comment |
up vote
0
down vote
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid
First of all, I would make sure that the owner is being persisted in the db, just to be sure that you have a value to be referencing
2-Should I create a table first with SQL using
Since you're using ORM, writing an SQL query would defeat the purpose of that, you could, but it's not all that necessary, since the relationships are specified already
3-Should I change my save method in TaskDAO?
4- Should I change my controller method(createTask method using RESTcall)
I think it would be best to change your createTask method, you could include the user's id as a pathvariable or a queryparameter and in that method you find the user using their id and set the user field in the task before passing it to the dto to save the value.
The reason the oid is null is because you do not have such a field in there.
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
In your task repository, you can create a method like
Collection<Task> findAllTasksByOwnerId(Long id);
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
You can specify the cascade type where you have specified the relationship between the task and the user
You can check this link for a simple tutorial on how to cascade in spring
add a comment |
up vote
0
down vote
up vote
0
down vote
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid
First of all, I would make sure that the owner is being persisted in the db, just to be sure that you have a value to be referencing
2-Should I create a table first with SQL using
Since you're using ORM, writing an SQL query would defeat the purpose of that, you could, but it's not all that necessary, since the relationships are specified already
3-Should I change my save method in TaskDAO?
4- Should I change my controller method(createTask method using RESTcall)
I think it would be best to change your createTask method, you could include the user's id as a pathvariable or a queryparameter and in that method you find the user using their id and set the user field in the task before passing it to the dto to save the value.
The reason the oid is null is because you do not have such a field in there.
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
In your task repository, you can create a method like
Collection<Task> findAllTasksByOwnerId(Long id);
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
You can specify the cascade type where you have specified the relationship between the task and the user
You can check this link for a simple tutorial on how to cascade in spring
1-What am I doing wrong? I just want to add a task with owner id to database, however it returns null as ownerid
First of all, I would make sure that the owner is being persisted in the db, just to be sure that you have a value to be referencing
2-Should I create a table first with SQL using
Since you're using ORM, writing an SQL query would defeat the purpose of that, you could, but it's not all that necessary, since the relationships are specified already
3-Should I change my save method in TaskDAO?
4- Should I change my controller method(createTask method using RESTcall)
I think it would be best to change your createTask method, you could include the user's id as a pathvariable or a queryparameter and in that method you find the user using their id and set the user field in the task before passing it to the dto to save the value.
The reason the oid is null is because you do not have such a field in there.
5- Assume that all of the problems above is fixed. How can I fetch all task that a user has?
In your task repository, you can create a method like
Collection<Task> findAllTasksByOwnerId(Long id);
6- How can I delete a task when a user is deleted(cascase in SQL, but is there any method in Hibernate)
You can specify the cascade type where you have specified the relationship between the task and the user
You can check this link for a simple tutorial on how to cascade in spring
answered Nov 10 at 9:10
Dean
12
12
add a comment |
add a comment |
up vote
0
down vote
The oid
is null because there is no such field in Task
. I think you are mixing two concepts here. The first one is the data transfer object that represents your REST data structure. This one should have an oid field. The second one is the persisting entity. This one you have, it's the Task
class.
I would implement a TaskDTO, use Hibernate's session to load the User
by its id, then build a Task
from the User
and the other fields from TaskDTO
, then save the Task like you do.
Regarding your other questions
2 - With a create
or update
value for hibernate.hbm2ddl.auto
, Hibernate can generate or update the tables when you start the application.
5 - You could have this interface
@GetMapping("/user/id")
public List<TaskDTO> getTasks(@PathVariable Long id)
Then I think you can't escape coding a criteria query of some sort.
6 - This is done with configuring the relation with cascade = CascadeType.ALL
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
|
show 5 more comments
up vote
0
down vote
The oid
is null because there is no such field in Task
. I think you are mixing two concepts here. The first one is the data transfer object that represents your REST data structure. This one should have an oid field. The second one is the persisting entity. This one you have, it's the Task
class.
I would implement a TaskDTO, use Hibernate's session to load the User
by its id, then build a Task
from the User
and the other fields from TaskDTO
, then save the Task like you do.
Regarding your other questions
2 - With a create
or update
value for hibernate.hbm2ddl.auto
, Hibernate can generate or update the tables when you start the application.
5 - You could have this interface
@GetMapping("/user/id")
public List<TaskDTO> getTasks(@PathVariable Long id)
Then I think you can't escape coding a criteria query of some sort.
6 - This is done with configuring the relation with cascade = CascadeType.ALL
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
|
show 5 more comments
up vote
0
down vote
up vote
0
down vote
The oid
is null because there is no such field in Task
. I think you are mixing two concepts here. The first one is the data transfer object that represents your REST data structure. This one should have an oid field. The second one is the persisting entity. This one you have, it's the Task
class.
I would implement a TaskDTO, use Hibernate's session to load the User
by its id, then build a Task
from the User
and the other fields from TaskDTO
, then save the Task like you do.
Regarding your other questions
2 - With a create
or update
value for hibernate.hbm2ddl.auto
, Hibernate can generate or update the tables when you start the application.
5 - You could have this interface
@GetMapping("/user/id")
public List<TaskDTO> getTasks(@PathVariable Long id)
Then I think you can't escape coding a criteria query of some sort.
6 - This is done with configuring the relation with cascade = CascadeType.ALL
The oid
is null because there is no such field in Task
. I think you are mixing two concepts here. The first one is the data transfer object that represents your REST data structure. This one should have an oid field. The second one is the persisting entity. This one you have, it's the Task
class.
I would implement a TaskDTO, use Hibernate's session to load the User
by its id, then build a Task
from the User
and the other fields from TaskDTO
, then save the Task like you do.
Regarding your other questions
2 - With a create
or update
value for hibernate.hbm2ddl.auto
, Hibernate can generate or update the tables when you start the application.
5 - You could have this interface
@GetMapping("/user/id")
public List<TaskDTO> getTasks(@PathVariable Long id)
Then I think you can't escape coding a criteria query of some sort.
6 - This is done with configuring the relation with cascade = CascadeType.ALL
edited Nov 10 at 9:15
answered Nov 10 at 9:03
Arthur Noseda
1,541818
1,541818
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
|
show 5 more comments
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
I don't want to use @GetMapping and id in the url field. I implemented a dummy task transfer object, which is almost identical to task object, but it has 'oid' rather than user object. To use 'posttask' object in postmapping, If I understand clearly, I must convert it to an entity. I've found that I can use convertToEntity method but IntelliJ cannot find it. Possibly I must first add the dependency in pom.xml, then import it
– i807055
Nov 10 at 9:25
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
You could certainly do that though I would advise you not to. In REST tradition, GET should be used when you retrieve data without changing anything in the system. POST on the contrary is the non-idempotent change. While it might seem clever on a short scale prototype, in a large scale application you definitely want you concepts (objects) to be aligned with some kind of perceived reality. As for convertToEntity, are you refering to the code in this article (baeldung.com/…) ?
– Arthur Noseda
Nov 10 at 9:45
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
Hmm. I though GET is used for getting information without changing anything on the backend server, POST is for creating an entity in the database(thus using body), PUT is for updating and DELETE self exploniatory. As you stated, I'm referencing to that website for convertToEntity method. However, I'm not sure that it is good for my application. Whole reason why I use Spring is not to create an instance. But it creates a ModelMapper, I couldn't find Autowired entity of that
– i807055
Nov 10 at 10:05
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I do the same when translating HTTP verbs to CRUD operations. POST for creating is certainly a non-idempotent change (though not all non-idempotent changes are creations) :-). I am not a big fan of automatic mappers because they tend to shift simple problems (forgetting to map a property) to complex ones (why does this automatic thingy does not do what I want). I think it depends on the team you're working in / with. The reason for using Spring in the first place should be for dependency injection, then for great interfacing with technologies and protocols.
– Arthur Noseda
Nov 10 at 10:31
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
I have little knowledge about Spring and other facilities :) I'm trying to learn new technologies and use them to increase my knowledge. Now, I have given up the ModelMapper mapper. I have created a taskDTO, and try to get information using getters and setters of taskDTO class, then find the user with that information. Still, the code does not compile because it cannot find taskDTO. I have created taskDTO in the same folder with task, and used @Entity annotation at the beginning of the class. Also imported it in the Controller class. What should I do more?
– i807055
Nov 10 at 10:35
|
show 5 more comments
up vote
0
down vote
The hibernate builds table and foreign keys automatically.Complex queries we can write in repo/controller in hibernate syntax.
With Crud repository we can delete , create update and read data easily.
for example we have student to course one to many relation.
@OneToMany
@JoinColumn(name = "studentId", referencedColumnName = "studentId", insertable = false, updatable = false)
private List<StudentCourses> studentCourses;
in StudentController I will write
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/registerStudentCourse", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public StudentCourses registerStudentCourse(@RequestBody StudentCourses studentCourse)
if (studentCourse != null)
studentCourse.setLastupdated(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
studentCourse = studentCourseRepository.save(studentCourse);
return studentCourse;
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/findStudentCourses", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public List<StudentCourses> findStudentCourses(@RequestBody String studentId)
List<StudentCourses> courses = new ArrayList<>();
JSONObject requestedJSONObject;
try
requestedJSONObject = new JSONObject(studentId);
String student = requestedJSONObject.getString("studentId");
courses =
studentCourseRepository.findCoursesByStudent(Long.parseLong(student));
catch (JSONException e)
// TODO Auto-generated catch block
return courses;
add a comment |
up vote
0
down vote
The hibernate builds table and foreign keys automatically.Complex queries we can write in repo/controller in hibernate syntax.
With Crud repository we can delete , create update and read data easily.
for example we have student to course one to many relation.
@OneToMany
@JoinColumn(name = "studentId", referencedColumnName = "studentId", insertable = false, updatable = false)
private List<StudentCourses> studentCourses;
in StudentController I will write
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/registerStudentCourse", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public StudentCourses registerStudentCourse(@RequestBody StudentCourses studentCourse)
if (studentCourse != null)
studentCourse.setLastupdated(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
studentCourse = studentCourseRepository.save(studentCourse);
return studentCourse;
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/findStudentCourses", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public List<StudentCourses> findStudentCourses(@RequestBody String studentId)
List<StudentCourses> courses = new ArrayList<>();
JSONObject requestedJSONObject;
try
requestedJSONObject = new JSONObject(studentId);
String student = requestedJSONObject.getString("studentId");
courses =
studentCourseRepository.findCoursesByStudent(Long.parseLong(student));
catch (JSONException e)
// TODO Auto-generated catch block
return courses;
add a comment |
up vote
0
down vote
up vote
0
down vote
The hibernate builds table and foreign keys automatically.Complex queries we can write in repo/controller in hibernate syntax.
With Crud repository we can delete , create update and read data easily.
for example we have student to course one to many relation.
@OneToMany
@JoinColumn(name = "studentId", referencedColumnName = "studentId", insertable = false, updatable = false)
private List<StudentCourses> studentCourses;
in StudentController I will write
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/registerStudentCourse", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public StudentCourses registerStudentCourse(@RequestBody StudentCourses studentCourse)
if (studentCourse != null)
studentCourse.setLastupdated(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
studentCourse = studentCourseRepository.save(studentCourse);
return studentCourse;
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/findStudentCourses", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public List<StudentCourses> findStudentCourses(@RequestBody String studentId)
List<StudentCourses> courses = new ArrayList<>();
JSONObject requestedJSONObject;
try
requestedJSONObject = new JSONObject(studentId);
String student = requestedJSONObject.getString("studentId");
courses =
studentCourseRepository.findCoursesByStudent(Long.parseLong(student));
catch (JSONException e)
// TODO Auto-generated catch block
return courses;
The hibernate builds table and foreign keys automatically.Complex queries we can write in repo/controller in hibernate syntax.
With Crud repository we can delete , create update and read data easily.
for example we have student to course one to many relation.
@OneToMany
@JoinColumn(name = "studentId", referencedColumnName = "studentId", insertable = false, updatable = false)
private List<StudentCourses> studentCourses;
in StudentController I will write
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/registerStudentCourse", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public StudentCourses registerStudentCourse(@RequestBody StudentCourses studentCourse)
if (studentCourse != null)
studentCourse.setLastupdated(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
studentCourse = studentCourseRepository.save(studentCourse);
return studentCourse;
@CrossOrigin(origins = "http://localhost:8090")
@RequestMapping(value = "/findStudentCourses", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE )
public List<StudentCourses> findStudentCourses(@RequestBody String studentId)
List<StudentCourses> courses = new ArrayList<>();
JSONObject requestedJSONObject;
try
requestedJSONObject = new JSONObject(studentId);
String student = requestedJSONObject.getString("studentId");
courses =
studentCourseRepository.findCoursesByStudent(Long.parseLong(student));
catch (JSONException e)
// TODO Auto-generated catch block
return courses;
answered Nov 10 at 12:05
M Faiz
13
13
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237271%2fhibernate-add-an-entity-with-foreign-key-using-rest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown