How can I add OneToMany association to an embedded type? - jpa

#Entity
#Data
#NoArgsConstructor //
#AllArgsConstructor
#EqualsAndHashCode
public class Decks{
#EmbeddedId
private DecksId decksId;
}
#Embeddable
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
public class DecksId implements Serializable{
private Integer id;
#OneToMany(mappedBy = "decksid",cascade = CascadeType.REMOVE)
private List<Deck> deck;
}
How can I make a #OneToMany association from DecksId.class to Deck.class? I have tried many things but none of them has worked. I would like to put many decks into decks.
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
public class Deck {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn
#JsonIgnore
private DecksId decksid;
}
In this case I get the following error code: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersRepository' defined

Related

spring data JPA OneToMany query pagination of child (many) table

I have the following code. The number of rows in the One table will be about 100 and the number of rows in the Many table will be several hundred thousand (millions). I'm going to need to paginate the Many rows per single row in One when I query.
I'm not sure how to accomplish this.
My first thought is to get only the rows (and NOT the manyList content) in One but not even sure of that in JPA OneManyRepository. And then for each row use it's id primary key to query the Many with that one_id value and do pagination that way.
Any help will be apprecited.
Thanks,Jim
public interface OneManyRepository extends JpaRepository<One, Long> {
#Query(value = "select one.id,one.columnOne,one.columnTwo from one", nativeQuery = true)
Optional<List<One2>> findAllOne();
#Query(value = "select many.someTimeValue,many.value from many where many.one_id = :id", nativeQuery = true)
Optional<List<Many>> findAllBy(#Param("id") long id);
}
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class One2 {
private Long id;
private String columnOne;
private String columnTwo;
}
#Entity
#Table(name = "one")
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class One {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
private Long id;
private String columnOne;
private String columnTwo;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "one")
private List<Many> manyList;
}
#Entity
#Table(name = "many")
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Many {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
private Long id;
#ManyToOne
private One one;
private long someTimeValue;
#Column(length = 10)
private String value;
}

Why JPA update entity causes stackoverflow?

I have an entity Task with id. Tasks belongs to Config. I need to update Task with it's Config doesn't change. Here is my code:
Task:
#Entity
#Getter
#Setter
public class Task{
#ManyToOne
#JoinColumn(name = "config_id", referencedColumnName = "id")
private Config config;
#OneToMany(orphanRemoval = true,cascade = CascadeType.ALL)
#JoinColumn(name="task_id")
private Set<ActivityItemTask> activityItemTasks = new HashSet<>();
}
#Entity
public class ActivityItemTask {
private Double score;
#EmbeddedId
private ActivityItemTaskId activityItemTaskId;
#Getter
#Setter
#Embeddable
#NoArgsConstructor
#AllArgsConstructor
public static class ActivityItemTaskId implements Serializable {
#ManyToOne
#JoinColumn(name = "activity_item_id")
private ActivityItem activityItem;
#ManyToOne
#JoinColumn(name = "task_id")
private Task task;
#ManyToOne
#JoinColumn(name = "config_id")
private TaskConfig config;
}
}
Config:
#Entity
#Getter
#Setter
public class Config{
#OneToMany(mappedBy = "config")
private Set<Task> tasks = new HashSet<>();
}
TaskService:
#Service
public class TaskService{
#Resource
TaskRepository taskRepository;
#Transactional
public Long save(Taskdto dto){
Config config = new Config();
config.setId(task.getConfigId());
s.setTaskConfig(config);
return taskRepository.save(s).getId();
}
}
TaskDto:
#Data
public class TaskDto {
private Long id;
#NotNull
private Long configId;
private String name;
private Date beginDate;
private Date endDate;
private String note;
}
when TaskService#save was called , it throw StackOverflowException:
org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.StackOverflowError
the log shows that my application querys task record and querys task's config and config's tasks and so on.
I am wondering what's wrong with my association annation. Any advice are appreciated.
I'm sorry.I have written another 2 calss so that I can find out the truth. It turns out my third calss ActivityItemTask may be the root cause. I think Task. activityItemTasks may should be annnotation with mappedBy=? But which field should be writtern here?
I did config wrong association.
Task should be :
#OneToMany(mappedBy = "activityItemTaskId.task")
// #JoinColumn(name = "task_id")
private Set<ActivityItemTask> activityItemTasks = new HashSet<>();
This is how to use mappedBy annotation with embedable class.
Thank all you guys commented or answered. You did help me find it out.

How to have version and audit information inside a nested object in springboot-MongoDB?

I have a version and auditing info in the #document class and it works fine.
Note:using this org.springframework.data.annotation.Version;
EmployeeModelDTO.java
#Getter
#Setter
#Builder
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
#NoArgsConstructor
#AllArgsConstructor
#Document(collection = "unt-employee")
public class EmployeeModelDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String type;
#Field("group")
private GroupDTO groupDTO;
#Id
#JsonAlias("id")
String id;
#Version
Integer schema_version;
#LastModifiedDate
LocalDateTime updatedDateTime;
#CreatedDate
LocalDateTime createdDateTime;
}
But if i try to put it inside a nested objects it is not getting inserted into mongo db
I need to have it inside GroupDTO.java
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
#NoArgsConstructor
#AllArgsConstructor
public class GroupDTO{
#Id
#JsonAlias("id")
String id;
#Version
Integer schema_version;
#LastModifiedDate
LocalDateTime updatedDateTime;
#CreatedDate
LocalDateTime createdDateTime;
}
So if I put the version and other info inside this class, it is not getting populated. Can any one let me know if having the version and other info inside the nested class is possible ?

Hibernate #OneToMany where discriminatorValue = 'SOMETHING'

Table pdp_billable_field_state carries configuration for various fields.
Owner of configuration can be any number of Entity`s
This configuration is same for each entity that matches the #DiscriminatorValue
#Getter
#Setter
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "entity_type")
#Table(name = "pdp_billable_field_state")
public abstract class EntityFieldStateJpa extends AuditableJPA {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "status_id")
private StatusJpa status;
#Column(name = "field", columnDefinition= "varchar(255)")
private String field;
private boolean disabled;
private boolean hidden;
}
#DiscriminatorValue("PURCHASE")
public class PurchaseEntityFieldStateJpa extends EntityFieldStateJpa {}
#Getter
#Setter
#Entity
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "pdp_purchase")
public class PurchaseJpa {
// omitted
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
// i do not have a join_column since all records with entity_type PURCHASE map to all purchases, as these are configurations used by all purchases. Should i try and introduce #JoinTable maybe?
#Where(clause = "entity_type='PURCHASE'")
private List<PurchaseEntityFieldStateJpa> fieldStates;
}

microservice seems to work, but there's no data displayed

I have a simple app that's supposed to connect to postgres and display content of one of the tables.
I installed postgres, created a table and inserted a row, but nothing is shown when I run it.
This are my application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=name
spring.datasource.password=pass
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
and this is repository interface
#Repository
public interface TaxonRepository extends CrudRepository<Taxon, Long> {
}
and the model
#Entity
#Table(name = "dim_taxon")
public class Taxon{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Getter #Setter
private Long id;
#Getter #Setter
private String name;
#Getter #Setter
private String value;
#Getter #Setter
private String reserve;
#Getter #Setter
private String source;
}
My service
#Service
public class TaxonService implements TaxonServiceI{
#Autowired
private TaxonRepository repository;
#Override
public List<Taxon> findAll() {
return (List<Taxon>) repository.findAll();
}
}
and controller
#Controller
public class TaxonController {
#Autowired
private TaxonServiceI taxonService;
#RequestMapping(value="/showTaxons")
public String homePage(Model model){
List<Taxon> taxons = taxonService.findAll();
model.addAttribute("taxons", taxons);
return "index";
}
}
I tried to add an object manually to check if there was a problem with the html or smth
List<Taxon> taxons = new ArrayList<>();
Taxon taxon1 = new Taxon();
taxon1.setName("a");
taxon1.setReserve("a");
taxon1.setSource("a");
taxon1.setValue("a");
taxons.add(taxon1);
model.addAttribute("taxons", taxons);
but html is fine. Seems like this
List<Taxon> taxons = taxonService.findAll();
doesn't work. What's the problem here? There aren't actually any errors.
My table and the data.
You are not adding your loaded List<Taxon> to the model.
#RequestMapping(value="/showTaxons")
public String homePage(Model model){
List<Taxon> taxons = taxonService.findAll();
return "index";
}
Just returns the page to render, without modifying the model.
So this should work
#RequestMapping(value="/showTaxons")
public String homePage(Model model){
model.add(taxonService.findAll());
return "index";
}
In the end I added a few more anotations
#Data
#NoArgsConstructor
#AllArgsConstructor
#Validated
#Entity
#Table(name = "table name")
And explicit mapping for columns
#Column(name = "column_name")
this helped