I need to convert a geojson to a WKB. Main Entity has now a field "Geojson" which is stored in Database(postgreSQL) as a String and I need another one "Geojson_WKB" or something similarly where I save the converted one.
Main Entity code:
#Getter
#Setter
#ToString
#RequiredArgsConstructor
#Entity
public class MainEntity extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Type(type = "json")
#Column(name = "geojson", columnDefinition = "jsonb")
private Geojson geojson;
//"Here should be another field with geojson_WKB"
GeoJson entity:
#Getter
#Setter
#ToString
#RequiredArgsConstructor
public class Geojson implements Serializable {
#Column(name = "type")
private String type;
#Type(type = "json")
#Column(name = "feature", columnDefinition = "jsonb")
private List<Feature> features;
}
Related
I am using queryDSL to fetch the inner collection of data and failed to do so. My entities are
#Entity
#Table(name = "countries")
#Setter
#Getter
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long countryId;
#Column(name = "name")
private String name;
#Column(name = "data")
private String data;
#OneToOne(mappedBy = "country")
private State stateJoin;
}
#Entity
#Table(name = "states")
#Setter
#Getter
public class State {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long stateId;
#Column(name = "name")
private String name;
#Column(name = "count")
private String count;
#Column(name = "co_id")
private Long countryId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "co_id", referencedColumnName = "id", updatable = false, insertable = false)
private Country country;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "state_id", referencedColumnName = "id")
private Set<Town> towns;
}
#Entity
#Table(name = "towns")
#Setter
#Getter
public class Town {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "town_id")
private Long townId;
#Column(name = "name")
private String name;
#Column(name = "people_count")
private String peopleCount;
#Column(name = "st_id")
private Long stateId;
}
and in querydsl i am trying below query and always failing to retrieve inner collection towns
List<Expression> childGroup = new ArrayList<>();
query.from(countries);
childGroup.addAll(Arrays.asList(countries.name, countries.data, countries.stateJoin));
query.join(countries.stateJoin, State);
childGroup.add(Projections.bean(State.class, name, count, town)
.as((Path) countries.stateJoin));
OR
childGroup.add(Projections.bean(State.class, name, count, list(town)).as((Path) countries.stateJoin));
query.select(fields);
query.where();
final Map<? extends Number, ? extends Object> t =
(Map<? extends Number, ? extends Object>)
query
.limit(pageRequest.getPageSize())
.offset(pageRequest.getOffset())
.distinct()
.transform(
GroupBy.groupBy(groupByPath)
.as(Projections.bean(Countris.class, childGroup.toArray(new Expression[0]))));
while executing the above line exactly i am getting always SQLSyntax error as i see the underlying SQL is with
. as towns
Can some one help me how to read the nested collection formed by JPA join?
I have started to use Hibernate with Panache in my projects.
Basic I have two entities QuestionGroup and Question.
#Entity
#Table(name = "tb006_question_groups")
public class QuestionGroup {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "question_group_id")
#Getter #Setter
private Long id;
#Column(name = "question_group_code")
#Getter #Setter
private String code;
#Column(name = "question_group_name")
#Getter #Setter
private String name;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_group_createdAt")
#Getter #Setter
private Date createdAt;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_group_updatedAt")
#Getter #Setter
private Date updatedAt;
#Column(name = "question_group_enabled")
#Getter #Setter
private Integer enabled;
#OneToMany(mappedBy="questionGroup", cascade = CascadeType.PERSIST)
#Getter #Setter
private List<Question> questions;
#Entity
#Table(name = "tb007_questions")
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "question_id")
#Getter #Setter
private Long id;
#Column(name = "question_name")
#Getter #Setter
private String name;
#Column(name = "question_answer")
#Getter #Setter
private String answer;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_createdAt")
#Getter #Setter
private Date createdAt;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_updatedAt")
#Getter #Setter
private Date updatedAt;
#Column(name = "question_enabled")
#Getter #Setter
private Integer enabled;
#ManyToOne
#JoinColumn(name="question_group_id", nullable=false)
#Getter #Setter
private QuestionGroup questionGroup;
This below, the method to insert the datas
#Transactional
#Override
public QuestionGroup createQuestionGroup(QuestionGroupCreateRequestDTO questionGroupCreate) {
QuestionGroup questionGroup =
this.convertQuestionGroupCreateToQuestionGroup(questionGroupCreate);
if (questionGroupCreate.getQuestions() != null) {
List<Question> questions = questionGroupCreate.getQuestions().stream().map(question -> this.convertQuestionCreateToQuestion(question)).collect(Collectors.toList());
questionGroup.setQuestions(questions);
}
questionGroupRepository.persist(questionGroup);
return questionGroup;
}
In my case, the entity QuestionGroup is persist correctly, after that my questions are not persisting and I am receiving this message: Column 'question_group_id' cannot be null
I am imaging the id from QuestionGroup not propagating to Question
How to resolve this problem without persist QuestionGroup and after create the Question objects?
Please initialize your list inside QuestionGroup:
#OneToMany(mappedBy="questionGroup", cascade = CascadeType.PERSIST)
#Getter #Setter
private List<Question> questions = new ArrayList<>();
Inside your QuestionGroup class put a helper method like this:
public void addQuestion(Question question) {
questions.add(question);
question.setQuestionGroup(this);
}
And change this line in your createQuestionGroup:
List<Question> questions = questionGroupCreate.getQuestions().stream().map(question -> this.convertQuestionCreateToQuestion(question)).collect(Collectors.toList());
to:
List<Question> questions = questionGroupCreate.getQuestions().stream().map(question -> {
var questionConverted = this.convertQuestionCreateToQuestion(question);
questionGroup.addQuestion(questionConverted);
}).collect(Collectors.toList());
I have the following entity in SpringBoot and I would like to create a new entity which has the userID of the registered user and the name of the registered/logged in user as instance fields/table columns.
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="User")
public class WebUser {
#Id
#GeneratedValue
private Long userID;
#NonNull
private String name;
#NonNull
private String email;
#NonNull
private String password;
}
How would I go about doing this using a form in SpringBoot and JPA entity? I am struggling, I tried to create a form with hidden input fields using #OneToMany annotation but the userID and name were null.
Thanks for any help
Frist of all you Should define table column names using #Column(name = "COLUMN_NAME") and assume your new entity name LogUser.
LogUser
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="LogUser")
public class LogUser{
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
private WebUser webUser;
#Column(name = "NAME", nullable = false)
private String name;
}
WebUser
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="User")
public class WebUser {
#Id
#GeneratedValue
#Column(name = "USER_ID")
private Long userID;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "EMAIL", nullable = false)
private String email;
#Column(name = "PASSWORD", nullable = false)
private String password;
#OneToMany(mappedBy = "webUser")
private Set<LogUser> logUsers;
}
I have a table master table user ,topics table and comments table
where in for a single topic there can be multiple comments
user table will be already populated.
I will get a post request to save the topic with structure like below
{
"topicId":"T001",
"title":"stackoverflow",
"commentBeans":[
{
"comment":"developer platform"
},
{
"comment":"developer communtiy"
}
]
}
Frameworks used:
spring boot
JPA
DB : postgressql
I am able to save the data the traditional way (i.e get the request and save topic bean first. get the primarykey from saved entity and loop the list of commentbean where user num will be set dynamically by another get service and save them)
I wanted to know if there is anyway to save the data with single save query.
#Entity
#Table(name ="user")
public class User implements Serializable {
#Id
#Column(name = "user_num")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userNum;
#Column(name = "user_id")
private String userId;
#Column(name = "username")
private String userName;
}
#Entity
#Table(name = "topics")
public class TopicBean implements Serializable {
#Id
#Column(name = "topic_num")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long topicNum;
#Column(name = "topicId")
private String topicId;
#Column(name = "title")
private String title;
#OneToMany(mappedBy="topicBean")
private List<CommentBean> commentBeans;
}
#Entity
#Table(name = "comments")
public class CommentBean implements Serializable {
#EmbeddedId
private CommentBeanKey key;
#Column(name = "comment")
private string comment;
#ManyToOne
#JoinColumn(name="topic_num")
private TopicBean topicBean;
#ManyToOne
#JoinColumn(name="user_num")
private TopicBean topicBean;
}
#Embeddable
public class CommentBeanKey implements Serializable{
private static final long serialVersionUID = 5889249943605061539L;
#Column(name ="topic_num")
private Long topicNum;
#Column(name ="user_num")
private Long userNum;
}
I saw the below link and am little worried if am doing the wrong way. any help is appreciated.
https://thoughts-on-java.org/hibernate-tips-how-to-map-an-entity-to-multiple-tables/
Parent.java
#Entity
#Table(name = "parent")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int parentId;
private String name;
#OneToMany(mappedBy="parent",fetch=FetchType.LAZY,cascade = CascadeType.PERSIST)
private List<Child> child = new ArrayList<Child>();
}
Child.java
#Entity
#Table(name = "child")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int childId;
private String account;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class)
#JoinColumn(name="parentId", referencedColumnName = "parentId", nullable = false)
private Parent parent;
}
Controller.java
//save Child with Parent at same
#PostMapping(value = "/onetomany")
public String OneToMany(#RequestBody Parent parent)
{
System.out.println("Parent: "+parent.toString());
for (Child child : parent.getChild()) {
child.setParent(parent);
}
parent.setChild(parent.getChild());
parentRepository.save(parent);
return "saved";
/*{
"name":"Romil",
"child":[
{"account":"1"},
{"account":"2"}
]
}*/
}
//save Child with Parent's ID
#PostMapping(value = "/onetomanyPID")
public String OneToMany(#RequestBody Child child)
{
child.setParent(child.getParent());
childRepository.save(child);
return "saved";
/*{
"account":"3",
"parent":{
"parentId":"1",
"name":"Romil"
}
}*/
}
I am trying to map a bidirectional One-to-Many relationship in Hibernate. In the build logs I receive the error "repeated column in mapping for entity."
What is generating the error?
The entity source code is below. One has a compound primary key. I am using Lombok to generate getters and setters.
The relationship: Award (One) --> AwardReceived (Many)
Award Entity
#Entity
#Table(name = "awards")
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class Award implements Serializable {
#Id
#Column(name = "award_id")
private Long awardId;
#OneToMany(cascade=CascadeType.ALL, mappedBy = "award")
private Set<AwardReceived> awardsReceived;
#Column(name = "award_type")
private String awardType;
#Column(name = "award")
private String award;
#Column(name = "description")
private String description;
}
AwardReceived Entity
#Entity
#Table(name = "awards_received")
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class AwardReceived implements Serializable{
#EmbeddedId
#JsonUnwrapped
private AwardReceivedPk awardReceivedPk;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "award_id")
private Award award;
#Column(name = "award_name")
private String awardName;
#Column(name = "citation")
private String citation;
}
AwardReceivedPk
#Embeddable
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class AwardReceivedPk implements Serializable{
#JsonIgnore
#Column(name = "client_no")
private String clientNo;
#Column(name = "award_id")
private Long awardId;
#Column(name = "year")
private Long year;
}
Please try
#ManyToOne(cascade=CascadeType.ALL)
private Award award;
instead of
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "award_id")
private Award award;