I'm working on a simple todo app in which you can add dependencies between todo items which means you cannot change status to true(completed) if dependency item is not completed. The problem is when I delete an item which another item is dependent to, json still shows dependency between two items. I'll try to explain with an example; say you have item 1 and item 2. Item 1 is dependent to item 2 and you can't mark item 1 "completed" if item 2 is not completed. But if you delete item 2 then dependency between items is also gone. So after deleting item 2 I can change item 1's status to true but when I make a get request for item 1, json still shows dependency to item 2.
Here is my TodoItem class;
package com.erdemkara.todoapp.data.entity;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Set;
#Entity
#Table(name = "todo_items")
public class TodoItem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(nullable = false)
private String name;
private String description;
#Column(nullable = false)
private LocalDate deadline;
#Column(nullable = false)
private boolean status;
#Column(name = "todo_list_id", nullable = false)
private int todoListId;
#OneToMany(mappedBy = "todoItem", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonManagedReference
private Set<Dependency> dependencies;
public TodoItem()
{}
public TodoItem(int id, String name, String description, LocalDate deadline,
boolean status, int todoListId, Set<Dependency> dependencies)
{
this.id = id;
this.name = name;
this.description = description;
this.deadline = deadline;
this.status = status;
this.todoListId = todoListId;
this.dependencies = dependencies;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDeadline() {
return deadline;
}
public void setDeadline(LocalDate deadline) {
this.deadline = deadline;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
#JsonGetter("todo_list_id")
public int getTodoListId() {
return todoListId;
}
public void setTodoListId(int todoListId) {
this.todoListId = todoListId;
}
public Set<Dependency> getDependencies() {
return dependencies;
}
public void setDependencies(Set<Dependency> dependencies) {
this.dependencies = dependencies;
}
}
Dependency class;
package com.erdemkara.todoapp.data.entity;
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
#Entity
#Table(name = "dependencies")
public class Dependency {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonIgnore
private int id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "todo_item_id", nullable = false)
#JsonBackReference
private TodoItem todoItem;
#Column(name = "dependency_item_id", nullable = false)
private int dependencyItemId;
public Dependency()
{}
public Dependency(int id, TodoItem todoItem, int dependencyItemId)
{
this.id = id;
this.todoItem = todoItem;
this.dependencyItemId = dependencyItemId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public TodoItem getTodoItem() {
return todoItem;
}
public void setTodoItem(TodoItem todoItem) {
this.todoItem = todoItem;
}
public int getDependencyItemId() {
return dependencyItemId;
}
public void setDependencyItemId(int dependencyItemId) {
this.dependencyItemId = dependencyItemId;
}
}
Response for item 1 get request(item 1 is dependent to item 2 and 3);
{
"id": 1,
"name": "Item 1",
"description": "Study Collections",
"deadline": "2023-01-09",
"status": false,
"dependencies": [
{
"dependencyItemId": 3
},
{
"dependencyItemId": 2
}
],
"todo_list_id": 1
}
I get the same response before and after deleting item 2. But I want to get a response like this;
{
"id": 1,
"name": "Item 1",
"description": "Study Collections",
"deadline": "2023-01-09",
"status": false,
"dependencies": [
{
"dependencyItemId": 3
}
],
"todo_list_id": 1
}
How can I fix this?
EDIT: #Zychoo I use 2 different delete methods on Service layer. One is for deleting all dependencies for an item. The other one is to delete a specific dependency;
public void deleteDependencyByDependencyItemId(int todoItemId, int dependencyItemId) {
dependencyRepository.deleteByDependencyItemId(todoItemId, dependencyItemId);
}
public void deleteAllDependenciesByTodoItemId(int todoItemId) {
dependencyRepository.deleteAll(dependencyRepository.findAllByTodoItemId(todoItemId));
}
And this is the Repository Layer;
public interface IDependencyRepository extends CrudRepository<Dependency, Integer> {
#Modifying
#Transactional
#Query(value = "delete from dependencies d where d.todo_item_id=? and d.dependency_item_id =?", nativeQuery = true)
void deleteByDependencyItemId(int todoItemId, int dependencyItemId);
}
You could changed
public Set<Dependency> getDependencies() {
return dependencies;
}
to
public Set<Dependency> getDependencies() {
return dependencies.stream().filter(dependency -> "your condition for completion").collect(Collectors.toSet());
}
The ObjectMapper from spring-boot uses the getters to create a JSON. If your Dependency does not show up in the return value of your getter, it will not show up in the JSON response.
I reorganized delete method in TodoItem service layer from this:
public void deleteItemById(int id) {
todoItemRepository.deleteById(id);
}
to this:
public void deleteItemById(int id) {
todoItemRepository.deleteById(id);
dependencyService.deleteAllDependenciesByTodoItemId(id);
}
It deletes every dependency along with the item. Now it works as I expected. Thank you for the answers.
Related
I can't seem to figure out how to add an entity that has a foreign key, though JSON.
I have a user model, and a post model.
A user can make different posts on a website.
This is a many-to-one relationship.
A user can have several posts, while a post can only have one user (the poster).
The post as a foreign key representing the id of the user that made the post.
This is the User model:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Table(name = "user")
public class User {
//ID
#Id
#SequenceGenerator(
name = "user_sequence",
sequenceName = "user_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.IDENTITY,
generator = "user_generator"
)
#Column(name = "id",nullable = false)
private int id;
private String username;
private String password;
private String email;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
#Column(name = "creation_date")
private Date creationDate;
//RELATIONSHIP
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<Post> posts = new ArrayList<>();
/* =========== GETTERS AND SETTERS ===========*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
}
This is the Post model:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Table(name = "post")
public class Post {
//ID
#Id
#SequenceGenerator(
name = "post_sequence",
sequenceName = "post_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.IDENTITY,
generator = "post_generator"
)
#Column(name = "id", nullable = false)
private int id;
#Column(name = "post_content")
private String postContent;
private String title;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
#Column(name = "creation_date")
private Date creationDate;
//RELATIONSHIP
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
/* ======== GETTERS AND SETTERS ======== */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
This is the postController:
#RestController
public class PostController {
#Autowired
private PostService postService;
#PostMapping("/savePost")
public Post getPost(#Validated #RequestBody Post post) {
return postService.savePost(post);
}
#GetMapping("getPost/{id}")
public Post getPost(#PathVariable int id) {
return postService.getPost(id);
}
#PutMapping("/deletePost/{id}")
public void deletePost(int id) {
postService.deletePost(id);
}
}
This is the JSON I send in to add a post.
Request to: http://localhost:8080/savePost
JSON body:
{
"postContent": "some content",
"creationDate": "2022-07-31",
"title": "my title",
"user": 1
}
But in postMan i get this error:
{
"timestamp": "2022-08-02T10:40:11.794+00:00",
"status": 400,
"error": "Bad Request",
"path": "/savePost"
}
And in spring i get this error:
JSON parse error: Cannot construct instance of x.model.User (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1);
If i send in a JSON where I call the user for "user_id" or "uderId", then Im able to send the request, but then the foreign key turns into null
{
"creationDate": "2022-07-31",
"postContent": "some content",
"title": "my title",
"user_id": 1
}
what gets sent in:
{
"id": 2,
"postContent": "some content",
"title": "my title",
"creationDate": "2022-07-31",
"user": null
}
Does anyone knwo what im doing wrong?
below is my stores enitity
#Entity
#Table(name="stores")
public class Stores {
#Id
#GeneratedValue
private Long id;
#Column(name ="incharge_id")
private Integer inchargeId;
#Column(name = "store_name")
private String storeName;
#OneToMany(mappedBy = "stores",
fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Items> items;
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
for (Items item : items) {
item.setStores(this);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getInchargeId() {
return inchargeId;
}
public void setInchargeId(Integer inchargeId) {
this.inchargeId = inchargeId;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
}
Below is my item entity
package bt.gov.dit.inventoryservice.model;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name = "items")
public class Items {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
#Column(name="item_name")
private String itemName;
#ManyToOne
private Categories categories;
#ManyToOne(fetch = FetchType.LAZY)
//#JoinColumn(name = "book_category_id", referencedColumnName = "id")
#JoinColumn(name = "stores_id", nullable = false,referencedColumnName = "id")
private Stores stores;
#Column(name="insert_date")
private Date insertDate;
#Column(name="update_date")
private Date updateDate;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Categories getCategories() {
return categories;
}
public void setCategories(Categories categories) {
this.categories = categories;
}
public Stores getStores() {
return stores;
}
public void setStores(Stores stores) {
this.stores = stores;
stores.getItems().add(this);
}
public Date getInsertDate() {
return insertDate;
}
public void setInsertDate(Date insertDate) {
this.insertDate = insertDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
}
I have one-to-many relationship between them. One store can have many items. But I don't know how to insert items with stores . I have tried the default save of Jpa respoistory but in place of stores_id (which is the foreign key) it saves null. Can anyone tell me how to implement the service?
It will be something like below.
Stores stores = new Stores();
stores.setStoreName("store name");
// Set other fields of store entity
Item item1 = new Item();
item1.setItemName("item name 1");
// Set other fields of item entity
Item item2 = new Item();
item2.setItemName("item name 2");
// Set other fields of item entity
// Call setItems
// Call getItems in a Set class object like Set<Item> items;
stores.setItems(items);
storesService.save(stores); // it will save all items with foreign key.
I am trying to have the api return a list of notes, associated by a many to many relationship with labels, given a label id. Spring boot automatically created a bridge table called notes_tables with a notes_id field and a labels_id field. Spring Boot also created a notes table and a labels table. I attempted the following:
#Query(value="select * from notes join notes_labels on note.id=notes_id join labels on labels_id=labels.id where labels_id=:lid", nativeQuery=true)
public List<Note> findNotesForLabel(#Param("lid") int labelId);
I just need to get this to work but I am specifically curious if I can get it to work with jpa method query. Any query will do as long as it works though.
EDIT:
Entities
Note.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "notes")
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany
#JsonIgnore
private List<Label> labels;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Folder getFolder() {
return folder;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Label> getLabels() {
return labels;
}
public void setLabels(List<Label> labels) {
this.labels = labels;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Note)) {
return false;
}
Note note = (Note) o;
return id == note.id && Objects.equals(note, note.note) &&
Objects.equals(title, note.title) && Objects.equals(status,
note.status) && Objects.equals(user, note.user) &&
Objects.equals(folder, note.folder) && Objects.equals(labels,
note.labels);
}
#Override
public int hashCode() {
return Objects.hash(id, note, title, status, user, folder,
labels);
}
}
Label.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "labels")
public class Label {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany(mappedBy = "labels")
#JsonIgnore
private List<Note> notes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Note> getNotes() {
return notes;
}
public void setNotes(List<Note> notes) {
this.notes = notes;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Label)) {
return false;
}
Label label = (Label) o;
return id == label.id && Objects.equals(title, label.title) &&
Objects.equals(status, label.status) && Objects.equals(user,
label.user) && Objects.equals(folder, label.folder) &&
Objects.equals(notes, label.notes);
}
#Override
public int hashCode() {
return Objects.hash(id, title, status, user, folder, notes);
}
}
Services:
NoteService.java
package com.example.maapi.services;
import com.example.maapi.models.Folder;
import com.example.maapi.models.Note;
import com.example.maapi.models.User;
import com.example.maapi.repositories.FolderRepo;
import com.example.maapi.repositories.NoteRepo;
import com.example.maapi.repositories.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class NoteService {
#Autowired
NoteRepo noteRepo;
#Autowired
UserRepo userRepo;
#Autowired
FolderRepo folderRepo;
public List<Note> findAllNotes(){
return noteRepo.findAllNotes();
}
public Note findNoteById(int noteId){
return noteRepo.findNoteById(noteId);
}
public List<Note> findNotesByUser(int userId){
return noteRepo.findNotesByUser(userId);
}
public Note createNoteForUser(int userId, Note note){
User user = userRepo.findUserById(userId);
note.setUser(user);
return noteRepo.save(note);
}
public List<Note> findNotesByFolder(int folderId){
return noteRepo.findNotesByFolder(folderId);
}
public Note createNoteForFolder(int folderId, Note note){
Folder folder = folderRepo.findFolderById(folderId);
note.setFolder(folder);
note.setUser(folder.getUser());
return noteRepo.save(note);
}
public int updateNote(int noteId, Note updatedNote){
Note note = noteRepo.findNoteById(noteId);
updatedNote.setUser(note.getUser());
updatedNote.setFolder(note.getFolder());
noteRepo.save(updatedNote);
if(updatedNote.equals(note)){
return 1;
} else {
return 0;
}
}
public int deleteNote(int noteId){
noteRepo.deleteById(noteId);
if(noteRepo.findNoteById(noteId) == null) {
return 1;
} else {
return 0;
}
}
// SEARCH IMPLEMENTATION
public List<Note> searchForNote(String note){
return noteRepo.searchForNote(note);
}
}
LabelService.java
So this is the spring-booty way to do this that I was able to figure out. CrudRepository has findById(Integer id) which returns an Optional object.
All you have to do is optional.get() to return the encapsulated object and then you can return the desired field (in my case List notes) with a getter.
// CrudRepo interface provides the findById method which returns an Optional<Label>
// object that may or may not exist. Optional.get() returns the encapsulated object.
public List<Note> findNotesByLabelId(int labelId) {
Optional<Label> label = labelRepo.findById(labelId);
return label.get().getNotes();
}
Try this one!
SELECT * FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1
Edit:
#Entity
#Table(name = "notes")
#NamedNativeQuery(name = "Note.getNoteByLabel", resultSetMapping = "getNote",
query = "SELECT n.id,n.note,n.title,n.status FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1")
#SqlResultSetMapping(name = "getNote", classes = #ConstructorResult(targetClass = Note.class,
columns = {#ColumnResult(name = "id", type = Integer.class),#ColumnResult(name = "note", type = String.class)
#ColumnResult(name = "title", type = String.class),#ColumnResult(name = "status", type = String.class)}))
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
NoteRepo.java
#Query(nativeQuery = true)
List<Note> getNoteByLabel(int labelId);
Build a proper constructor and try this one.
You have to think on it as if it was simple POO. For example, you can use:
#Query("FROM Note n WHERE (SELECT l FROM Label l WHERE l.id = :lid) MEMBER OF labels")
public List<Note> findNotesByLabel(#Param("lid") int id);
which basically means,
get all notes where given id's label is part of the labels attribute
I don't fully know each implementation yet, surely the documentation would give a better approach, but I just came up with that problem and it did the trick
I have the following entities defined:
Restaurante:
#Entity
#Table(name = "restaurantes")
public class Restaurante implements Serializable {
private int id;
private Set<Menu> menus = new HashSet<>(0);
public Restaurante() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "restaurante_id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonIgnore
#OneToMany(mappedBy = "restaurante")
public Set<Menu> getMenus() {
return menus;
}
public void setMenus(Set<Menu> menus) {
this.menus = menus;
}
}
And menu:
#Entity
#Table(name = "menus")
public class Menu implements Serializable {
private int id;
private Restaurante restaurante;
public Menu() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "menu_id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "restaurante_id", nullable = false)
public Restaurante getRestaurante() {
return restaurante;
}
public void setRestaurante(Restaurante Restaurante) {
this.restaurante = restaurante;
}
}
And when I perform the following query:
public Menu getMenuById(Integer id) throws HibernateException, IndexOutOfBoundsException {
session = HibernateSessionService.getSessionFactory().openSession();
criteria = session.createCriteria(Menu.class)
.add(Restrictions.eq("id", id));
return (Menu) criteria.list().get(0);
}
The property restaurante is null.
There is a restaurante loaded in the database with the Id I'm using, and there are several menus loaded with that foreign key as well.
Can someone give me advice or help me?
Thanks in advance!
Apache camel is using a route wich is listening to a specific url. the json from this url is then transformed to pojo classes and inserted in a mySQL database. Everything is working fine, except my foreign key still remains null. I'm using spring framework btw.
Here is the url where you can find the data:
https://builds.apache.org:443/job/Accumulo-1.5/api/json
Here is my routedefinition for camel
#Component
public class JenkinsConfigurationRouteBuilder extends SpringRouteBuilder {
private Logger logger = LoggerFactory.getLogger(JenkinsConfigurationRouteBuilder.class);
#Override
public void configure() throws Exception {
logger.info("Configuring route");
//Properties die hij niet vindt in de klasse negeren
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
DataFormat jenkinsConfigFormat = new JacksonDataFormat(objectMapper, JenkinsConfiguration.class);
from("timer://foo?fixedRate=true&delay=0&period=200000&repeatCount=1")
.routeId("jsonToJenkinsConfiguration")
.setHeader(Exchange.HTTP_METHOD, constant("GET"))
.to("https://builds.apache.org:443/job/Accumulo-1.5/api/json")
.convertBodyTo(String.class)
.unmarshal(jenkinsConfigFormat) //instance van JenkinsConfiguration
.log(LoggingLevel.DEBUG, "be.kdg.teamf", "Project: ${body}")
.to("hibernate:be.kdg.teamf.model.JenkinsConfiguration");
}
}
My POJO class
#Entity(name = "jenkinsConfiguration")
public class JenkinsConfiguration extends Configuration implements Serializable {
#Column
#JsonProperty("displayName")
private String name;
#JsonProperty("healthReport")
#JsonIgnore
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("jenkinsConfig"))
private Collection<HealthReport> healthReport;
#JsonProperty("builds")
#JsonIgnore
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("jenkinsConfig"))
private Collection<Build> builds;
#JsonProperty("modules")
#JsonIgnore
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = ("jenkinsConfig"))
private Collection<Module> modules;
public JenkinsConfiguration() {
}
public JenkinsConfiguration(Collection<Build> builds, Collection<HealthReport> healthReport, Collection<Module> modules, String name) {
this.builds = builds;
this.healthReport = healthReport;
this.modules = modules;
this.name = name;
}
public Collection<Build> getBuilds() {
return builds;
}
public Collection<HealthReport> getHealthReport() {
return healthReport;
}
public Collection<Module> getModules() {
return modules;
}
public String getName() {
return name;
}
public void setBuilds(Collection<Build> builds) {
this.builds = builds;
}
public void setHealthReport(Collection<HealthReport> healthReport) {
this.healthReport = healthReport;
}
public void setModules(Collection<Module> modules) {
this.modules = modules;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
Let us take the builds for instance.
As you can see, this pojo class contains a list from builds. A JenkinsConfiguration can contain more builds. One build belongs to one JenkinsConfiguration.
This is my Build class:
#XmlRootElement(name = "builds")
#Entity(name = "build")
public class Build implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
#Column
#JsonProperty("number")
private Integer number;
#Column
#JsonProperty("url")
private String url;
#JsonBackReference
#OnDelete(action = OnDeleteAction.CASCADE)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "jenkinsConfig")
private JenkinsConfiguration jenkinsConfig;
public Build() {
}
public Build(JenkinsConfiguration jenkinsConfig, Integer number, String url) {
this.jenkinsConfig = jenkinsConfig;
this.number = number;
this.url = url;
}
public int getId() {
return Id;
}
public JenkinsConfiguration getJenkinsConfig() {
return jenkinsConfig;
}
public Integer getNumber() {
return number;
}
public String getUrl() {
return url;
}
public void setId(int id) {
Id = id;
}
public void setJenkinsConfig(JenkinsConfiguration jenkinsConfig) {
this.jenkinsConfig = jenkinsConfig;
}
public void setNumber(Integer number) {
this.number = number;
}
public void setUrl(String url) {
this.url = url;
}
}
My question: how come that my foreign key is not set for the build class? it remains null.
Doe I need to update it manually or something? If so, how do I do that in spring?
Any help would me much appreciated!
Fixed it by updating the records in my database like so:
Camel:
from("hibernate:be.kdg.teamf.model.Build?delay=1s")
.routeId("buildFkBuild")
.startupOrder(3)
.shutdownRunningTask(ShutdownRunningTask.CompleteAllTasks)
.to("bean:buildFK?method=processBuild")
.log(LoggingLevel.DEBUG, "be.kdg.teamf", "Project: ${body}")
.to("hibernate:be.kdg.teamf.model.Build");
Bean:
#Consumed
public Build processBuild(Build build) {
//updaten van foreign key
build.setJenkinsConfig(jenkinsConfiguration);
return build;
}