I'm new at Spring Boot's JPA concept so need your help in deciding how to import the ID of another entity and ArrayList of Ids of another entity. I want to create a board, providing an account's Id and ArrayList of Ids of accounts.
Following are my Account and Board entities:
#Entity(name = "Account")
#Table(name = "account", uniqueConstraints = {#UniqueConstraint(name = "account_email_unique", columnNames = "email")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "account_id")
private Integer accountId;
#JsonIgnore
#OneToMany(targetEntity = Board.class, mappedBy = "boardOwnerId")
private Set<Board> boardSet = new HashSet<>();
#JsonIgnore
#ManyToMany(mappedBy = "boardMembers")
private Set<Board> boards = new HashSet<>();
#Entity(name = "Board")
#Table(name = "board", uniqueConstraints = {#UniqueConstraint(name = "board_name_unique", columnNames = "name")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Board {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "board_id")
private Integer boardId;
#ManyToOne(targetEntity = Account.class, cascade = CascadeType.ALL)
#JoinColumn(name = "account_id", referencedColumnName = "account_id")
private Account boardOwnerId;
#ManyToMany
#JoinTable(name = "board_member", joinColumns = #JoinColumn(name = "board_id"), inverseJoinColumns =
#JoinColumn(name = "account_id"))
private Set<Account> boardMembers = new HashSet<>();
#Repository
public interface BoardRepository extends JpaRepository<Board, Integer> {
}
#RestController
#RequestMapping("/boards")
public class BoardController {
private final BoardService boardService;
#Autowired
public BoardController(BoardService boardService) {
this.boardService = boardService;
}
#PostMapping("/create-board")
ResponseEntity<BoardDtoResponse> createBoard(#Valid #RequestBody BoardDto boardDto) {
return new ResponseEntity<>(boardService.createBoard(boardDto), HttpStatus.CREATED);
}
}
#Service
public class BoardServiceImpl implements BoardService {
private final BoardRepository boardRepository;
private final ModelMapper modelMapper;
#Autowired
public BoardServiceImpl(BoardRepository boardRepository) {
this.boardRepository = boardRepository;
modelMapper = new ModelMapper();
}
#Override
public BoardDtoResponse createBoard(BoardDto boardDto) {
Board boardToSave = modelMapper.map(boardDto, Board.class);
Board newBoard = boardRepository.save(boardToSave);
return modelMapper.map(newBoard, BoardDtoResponse.class);
}
}
I can successfully create an account, but when I want to create a board and pass boardOwnerId and membersIds, it creates a board, but boardOwnerId and membersIds are set to null.
Here is the request via Postman:
Thanks in advance for your time!
As far as I have seen, you should change the mapping between the two entities for both mappings. Let me explain:
For the mapping of the board owner (#OneToMany) try to maintain only that one annotation and remove the property with #ManyToOne from Board entity. In addition, change the properties values of the #OneToMany annotation and add a #JoinColumn with next values:
#Entity(name = "Account")
#Table(name = "account", uniqueConstraints = {#UniqueConstraint(name = "account_email_unique", columnNames = "email")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "account_id")
private Integer accountId;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "boardOwnerId")
private Set<Board> boardSet = new HashSet<>();
...
#Entity(name = "Board")
#Table(name = "board", uniqueConstraints = {#UniqueConstraint(name = "board_name_unique", columnNames = "name")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Board {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "board_id")
private Integer boardId;
...
This is known as a One To Many unidirectional mapping (https://www.bezkoder.com/jpa-one-to-many-unidirectional/).
On the other hand you could try to maintain only the #ManyToOne annotation on Board entity, but remove the property with #OneToMany annotation from Account entity with next properties values:
#Entity(name = "Account")
#Table(name = "account", uniqueConstraints = {#UniqueConstraint(name = "account_email_unique", columnNames = "email")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "account_id")
private Integer accountId;
...
#Entity(name = "Board")
#Table(name = "board", uniqueConstraints = {#UniqueConstraint(name = "board_name_unique", columnNames = "name")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Board {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "board_id")
private Integer boardId;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "account_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Account boardOwnerId;
...
This is known as the default One To Many mapping (https://www.bezkoder.com/jpa-one-to-many/).
In any case, you see you only have to implement one of the two types of annotations for a One To Many mapping.
And last, for the #ManyToMany mappings, try the next implementation (adding fetch and cascade properties values):
#Entity(name = "Account")
#Table(name = "account", uniqueConstraints = {#UniqueConstraint(name = "account_email_unique", columnNames = "email")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Account {
...
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "boardMembers")
#JsonIgnore
private Set<Board> boards = new HashSet<>();
#Entity(name = "Board")
#Table(name = "board", uniqueConstraints = {#UniqueConstraint(name = "board_name_unique", columnNames = "name")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Board {
...
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "board_member", joinColumns = #JoinColumn(name = "board_id"), inverseJoinColumns =
#JoinColumn(name = "account_id"))
private Set<Account> boardMembers = new HashSet<>();
You can find this implementation design here: https://www.bezkoder.com/jpa-many-to-many/
The problem was that the entity was not mapping properly with dto. The solution is explicit mapping plus the answer of Gescof.
Here I found information about explicit mapping: ModelMapper mapping the wrong id
Changed code in the service class:
#Service
public class BoardServiceImpl implements BoardService {
private final BoardRepository boardRepository;
private final ModelMapper modelMapper;
#Autowired
public BoardServiceImpl(BoardRepository boardRepository) {
this.boardRepository = boardRepository;
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
}
#Override
public BoardDtoResponse createBoard(BoardDto boardDto) {
Board boardToSave = modelMapper.map(boardDto, Board.class);
Board newBoard = boardRepository.save(boardToSave);
return modelMapper.map(newBoard, BoardDtoResponse.class);
}
}
Changed code in the entity classes:
#Entity(name = "Account")
#Table(name = "account", uniqueConstraints = {#UniqueConstraint(name = "account_email_unique", columnNames = "email")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "account_id")
private Integer accountId;
#JsonIgnore
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "boardMembers")
private Set<Board> boards = new HashSet<>();
#Entity(name = "Board")
#Table(name = "board", uniqueConstraints = {#UniqueConstraint(name = "board_name_unique", columnNames = "name")})
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Board {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "board_id")
private Integer boardId;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "account_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Account boardOwnerId;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "board_member", joinColumns = #JoinColumn(name = "board_id"), inverseJoinColumns =
#JoinColumn(name = "account_id"))
private Set<Account> boardMembers = new HashSet<>();
I've created an API that has actor, movie and category entities. Actor and movie are connected by many-to-many relationship that maps to a join table called movie_actor and category is connected with movie by one-to-many relationship.
I'm trying to write a native query that returns an integer that would represent the amount of movies from a specific category where specific actor has played so for example query would return 2 if actor played in 2 different sci-fi movies. I have no problem doing that from the database level where I can see the join table movie_actor but that table remains unaccessible in my api because it's not a separate entity. How can I create it that it automatically maps actor and movie ids as the movie_actor table ?
Here is an example code that works for me in the H2 Database:
SELECT COUNT(*) FROM MOVIE M JOIN MOVIE_ACTOR MA on M.MOVIE_ID = MA.MOVIE_ID WHERE ACTOR_ID = 1 AND CATEGORY_ID = 1
Here are my entities:
Actor:
#Entity
#Data
#Table(name = "actor")
#AllArgsConstructor
#NoArgsConstructor
public class Actor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "actor_id")
private long actorId;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
#Nullable
#ManyToMany(mappedBy = "actors", fetch = FetchType.EAGER)
#JsonBackReference
private List<Movie> movies = new ArrayList<>();
public Actor(String name, String surname){
this.name = name;
this.surname = surname;
}
}
Movie:
#Entity
#Data
#Table(name = "movie")
#AllArgsConstructor
#NoArgsConstructor
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "movie_id")
private long movieId;
#Column(name = "title")
private String title;
#ManyToMany
#JoinTable(
name = "movie_actor",
joinColumns = #JoinColumn(name = "movie_id"),
inverseJoinColumns = {#JoinColumn(name = "actor_id")}
)
#JsonManagedReference
private List<Actor> actors = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "CATEGORY_ID")
#JsonManagedReference
private Category category;
}
So you have to make it accessible in your API. One option would be to map the intersection table movie_actor to the entity MovieActor and split ManyToMany relationship between Actor and Movie to OneToMany relationship with MovieActor, like that:
#Entity
#Data
#Table(name = "movie_actor")
#AllArgsConstructor
#NoArgsConstructor
public class MovieActor {
#EmbeddedId
private MovieActorId productOrderId = new MovieActorId();
#ManyToOne(cascade = CascadeType.ALL, optional = false)
#MapsId("movieId")
#JoinColumn(name = "product_id", nullable = false)
private Movie movie;
#ManyToOne(cascade = CascadeType.ALL, optional = false)
#MapsId("actorId")
#JoinColumn(name = "order_id", nullable = false)
private Actor actor;
public void addMovieActor(Movie aMovie, Actor aActor) {
movie = aMovie;
actor = aActor;
aMovie.getMovieActors().add(this);
aActor.getMovieActors().add(this);
}
}
#Embeddable
#Getter
#Setter
public class MovieActorId implements Serializable {
#Column(name = "movie_id")
private Long movieId;
#Column(name = "actor_id")
private Long actorId;
}
#Entity
#Data
#Table(name = "actor")
#AllArgsConstructor
#NoArgsConstructor
public class Actor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "actor_id")
private long actorId;
#OneToMany(mappedBy = "actor")
private List<MovieActor> movieActors = new ArrayList<>();
}
#Entity
#Data
#Table(name = "movie")
#AllArgsConstructor
#NoArgsConstructor
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "movie_id")
private long movieId;
#OneToMany(mappedBy = "movie")
private List<MovieActor> movieActors = new ArrayList<>();
}
Now you can access the intersection table MovieActor inside the query. You can even add more columns to this table if you want.
I'm trying to set simple entity with NamedEntityGraph on it. Unfortunately it won't work. Could you have any ideas how to fix it?
ServiceType entity has #ElementCollection of with Set of String which are simply ids of PictureModel associated with entity. On run I got:
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [backgroundPicIds] on this ManagedType [pl.mihome.djcost.model.ServiceType]
#Entity
#Table(name = "service_type")
#Getter
#Setter
#NoArgsConstructor
#NamedEntityGraph(
name = "serviceType.with.backgroundPicIds",
attributeNodes = #NamedAttributeNode("backgroundPicIds")
)
public class ServiceType {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Setter(AccessLevel.NONE)
#Column(nullable = false, updatable = false)
private int id;
#Length(max = 100)
#NotBlank
private String name;
private boolean active;
#OneToMany(mappedBy = "serviceType")
private Set<Account> accounts;
#ManyToMany(mappedBy = "servicesApplicable")
private Set<AccountType> accountTypes;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "serviceType", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<PictureModel> backgroundPicture;
#ElementCollection
#CollectionTable(name = "image", joinColumns = {#JoinColumn(name = "service_type_id")})
#Column(name = "id")
private Set<String> backgroundPictureId;
#PrePersist
void activate() {
this.active = true;
}
}
#Entity
#Table(name = "image")
#NoArgsConstructor
#Getter
#Setter
#Builder
#AllArgsConstructor
public class PictureModel {
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
#Column(nullable = false, updatable = false)
#Setter(AccessLevel.NONE)
private String id;
private String type;
private String name;
#Lob
private byte[] body;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "account_id")
private Account account;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "public_platform_id")
private PublicPlatform publicPlatform;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "service_type_id")
private ServiceType serviceType;
}
You simply do not have an attribute with the name backgroundPicIds in the entity ServiceType.
Try to correct your graph in this way:
#NamedEntityGraph(
name = "serviceType.with.backgroundPicIds",
attributeNodes = #NamedAttributeNode("backgroundPictureId")
)
I design a system of tables in the database for the film service. So far I have designed them in this way.
#Entity
#Table(name = "movies")
#Data
public class MovieEntity {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
private Set<MovieDescription> description;
}
#Entity
#Table(name = "movies_info")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type")
public abstract class MovieInfo {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#ManyToOne
public MovieEntity movie;
}
#Entity
#DiscriminatorValue(value = EditType.Values.DESCRIPTION)
public class MovieDescription extends MovieInfo {
private String description;
private String language;
}
When compiling, it sends me a mistake
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.core.jpa.entity.MovieDescription.movie in com.core.jpa.entity.MovieEntity.description
Something related to MovieEnity mapping, but I don't know what it is all about.
use targetEntity attribute to target the super class field that you want to map with.
#Entity
#Table(name = "movies")
#Data
public class MovieEntity {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "movie", cascade = CascadeType.ALL, targetEntity= MovieInfo.class)
private Set<MovieDescription> description;
}
More detail: one to many mapping to a property of superclass
How select records without parent with Hibernate using Criteria API?
Here is my Java code for select with parents
getSessionFactory().getCurrentSession().createCriteria(Category.class).add(
Restrictions.eq("parent", new Category(parentId))).list();
Category Java code
#Entity
#Table(name = "CATEGORY")
public class Category implements NamedModel{
#Id
#Column(name = "CATEGORY_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
#JoinTable(name = "CATEGORY_RELATIONS",
joinColumns = {
#JoinColumn(name = "CATEGORY_RELATIONS_CATEGORY_ID", referencedColumnName = "CATEGORY_ID")},
inverseJoinColumns = {
#JoinColumn(name = "CATEGORY_RELATIONS_PARENT_ID", referencedColumnName = "CATEGORY_ID")})
private Category parent;
#OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "parent")
private List<Category> children;//...
}
CategoryRelations Java code
#Entity
#Table(name = "CATEGORY_RELATIONS")
#IdClass(CategoryRelations.CategoryRelationsPrimaryKey.class)
public class CategoryRelations implements Serializable {
#Id
#Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
private long categoryId;
#Id
#Column(name = "CATEGORY_RELATIONS_PARENT_ID")
private long parentId;
#Entity
#IdClass(CategoryRelationsPrimaryKey.class)
public static class CategoryRelationsPrimaryKey implements Serializable {
private long categoryId;
private long parentId;
}
}
You can use Restriction#isNull(propertyName) function for your requirements.
Restrictions.isNull("parent")