Java hql query issue - java

I want to get all the messages of the all user's subscribers with sql or hql. But i don't know how
I want to create the page with messages of all user's subscribers like in twitter or other social networks
I would appreciate any help
Message entity:
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "msg_seq")
#SequenceGenerator(name = "msg_seq", sequenceName = "msg_seq", initialValue = 1, allocationSize = 1)
#Column(name = "id")
private Integer id;
#Column(name = "text")
private String text;
#Column(name = "tag")
private String tag;
#ManyToOne
#JoinColumn(name = "user_id")
private User author;
#Column(name = "header")
private String header;
#Column(name = "like_count")
private Integer likeCount = 0;
#ManyToMany
#JoinTable(
name = "message_likes",
joinColumns = {#JoinColumn(name = "message_id")},
inverseJoinColumns = {#JoinColumn(name = "user_id")}
)
private Set<User> likes;
#OneToOne
#JoinColumn(name = "file_id")
private FileEntity fileEntity;
}
User entity:
public class User {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "usr_seq")
#SequenceGenerator(name = "usr_seq", sequenceName = "usr_seq", initialValue = 1, allocationSize = 1)
#Column(name = "id")
private Long id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "role")
private Role role;
#Column(name = "email")
private String email;
#Column(name = "status")
private Status status;
#Column(name = "subscriber_count")
private Integer subscriberCount = 0;
#Column(name = "subscription_count")
private Integer subscriptionCount = 0;
#OneToOne
#JoinColumn(name = "gender_id")
private Gender gender;
#OneToOne
#JoinColumn(name = "address_id")
private Address address;
#ManyToMany
#JoinTable(
name = "user_subscriptions",
joinColumns = #JoinColumn(name = "channel_id"),
inverseJoinColumns = #JoinColumn(name = "subscriber_id"))
private Set<User> subscribers;
#ManyToMany
#JoinTable(
name = "user_subscriptions",
joinColumns = #JoinColumn(name = "subscriber_id"),
inverseJoinColumns = #JoinColumn(name = "channel_id"))
private Set<User> subscriptions;
#OneToOne
#JoinColumn(name = "file_id")
private FileEntity fileEntity;
}
I tried to write this query for my jpa repository but i couldn't

Related

How to get the details of farmer in spring boot using the UserServiceImpl?

How to view details of farmer through the userServiceImpl class? We cant use the farmerServiceImpl as we have to pass the username as the input not the id and username is not present in farmerClass.
User class:
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotBlank(message = "Username is mandatory")
#Size(max = 20)
private String username;
#NotBlank(message = "Password is mandatory")
#Size(max = 50)
private String password;
#ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST})
#JoinTable(name = "user_roles",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
#OneToOne(fetch = FetchType.LAZY,
cascade = {CascadeType.REMOVE,CascadeType.PERSIST},
mappedBy = "user")
#JsonIgnore
private Farmer farmer;
}
Farmer Class:
public class Farmer {
#Id
#GeneratedValue
private int farmerId;
#NotBlank
#Size(max = 120)
private String name;
#NotBlank
#Size(max = 120)
private String address;
#NotBlank
#Size(max = 12)
private String phoneNo;
// OneToOne unidirectional relationship
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private User user;
}
UserServiceImpl :
public User viewUser(String username) {
<<<How to viewdetails of farmer class through this method>>>
}

Sorting using hibernate

I have to ask you question about sorting using hibernate, because I absolutely don't know how to resolve my problem, because right now I am on the project, which has been implemented with lot of problems and right know I am standing on one of them.
I have these three model classes.
First one is Document, second one is CustomProperty and the LastOne is CustomPropertyDefinition.
#Indexed
#Table(name = "documents")
#EntityListeners({ AuditingEntityListener.class })
#JsonIgnoreProperties(value = { "isLogicallyDeleted", "textContent", })
public class Document {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column(name = "id", length = 40)
private String id;
#Field
#Column(name = "title", nullable = false)
private String title;
#Field
#Column(name = "mimetype", nullable = false)
private String mimetype;
#Field
#Column(name = "creator")
private String creator;
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
#Column(name = "created")
private Date created;
#Field
#Column(name = "modifier")
private String modifier;
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
#Column(name = "modified")
private Date modified;
#Field
#Column(name = "folder_id", length = 40)
private String folderId;
#Column(name = "Ordering")
private Date ordering;
#Column(name = "definition_id", length = 40)
private String definitionId;
#OneToMany(mappedBy = "parentDocument", cascade = CascadeType.ALL, orphanRemoval = true)
#JsonManagedReference
private Set<CustomProperty> customProperties = new HashSet<CustomProperty>();
Custom Property :
#Indexed
#Table(name = "custom_properties")
#JsonIgnoreProperties(value = "stringValue")
public class CustomProperty {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column(name = "id", length = 40)
private String id;
#Column(name = "definition_id", nullable = false, length = 40)
private String definitionId;
#Field
#Column(name = "value")
private String stringValue;
#Transient
private String title;
#Transient
private Object value;
#IndexedEmbedded
#ManyToOne
#JoinColumn(name = "document_id", referencedColumnName = "id", updatable = true)
#JsonBackReference
private Document parentDocument;
And CustomPropertyDefinition :
#Entity
#Table(name = "custom_property_definitions")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "definitionsUsedIn" })
public class CustomPropertyDefinition {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column(name = "id", length = 40)
private String id;
#Column(name = "property_type", nullable = false, length = 10)
private String propertyType;
#Column(name = "symbolic_name", unique = true, nullable = false)
private String symbolicName;
#Column(name = "lower_bound")
private String lowerBound;
#Column(name = "upper_bound")
private String upperBound;
#ElementCollection
#CollectionTable(name = "custom_property_definition_allowed_values", joinColumns = #JoinColumn(name = "id"))
#Cascade(CascadeType.ALL)
#Column(name = "allowedValue")
#OrderBy("allowedValue ASC")
private Set<String> allowedValues;
#Transient
private Set<String> allowedValuesToAdd = new HashSet<String>();
#ManyToMany(mappedBy = "customPropertyDefinitions")
private Set<DocumentClassDefinition> definitionsUsedIn;
#ManyToMany(mappedBy = "custPropDefinitions")
private Set<PropertyFolderStructure> propertyFolderStructure;
I am using pagination for returning the documents, but I need to have sorted attribute of Document " CustomProperty " by Attribute of "CustomPropertyDefinition " - > symbolicName . Do you have any idea how to sort it ?
Thank you very much! Every advice for me is great!

Spring Cannot add foreign key constraint #ManyToOne

I've tried to make this Entity:
#Entity
#Table(name = "rate")
public class Rate {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "rate_id")
private Long id;
#ManyToOne
#JoinColumn(name = "user_id")
private User answerer;
#ManyToOne
#JoinColumn(name = "answer_id")
private Answer answer;
#Column(name = "rate_rate")
private Integer rate = AnswerConstants.MAX_RATE;
//pluss getter-setters
}
Unfortunately, I get this error:
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table rate add constraint FK8totaejp8tp48clsoikn05fn2 foreign key (answer_id) references answer (answer_id)]
I've Googled for about an hour but I could not found the solution. Can you help me? Why am I getting this?
Additionally: spring.jpa.hibernate.ddl-auto=update, if I turn it off, it solves the problem but I do not want to do that just because of this.
The Answer class looks like this:
#Entity
#Table(name = "answer")
public class Answer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "answer_id")
private Long id;
#Column(name = "answer_text")
#NotEmpty
private String answerText;
#ManyToOne
#JoinColumn(name = "user_id")
private User answerCreator;
#ManyToOne
#JoinColumn(name = "question_id")
private Question question;
#Column(name = "answer_creation_date")
#NotNull
private Date creationDate = new Date();
#Column(name = "answer_rate")
private Long answerRate = 1l;
//plus getters-setters
}
And the User class:
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private Long id;
#Column(name = "email")
#Email(message = "*Please provide a valid Email")
#NotEmpty(message = "*Please provide an email")
private String email;
#Column(name = "password")
#Length(min = 5, message = "*Your password must have at least 5 characters")
#NotEmpty(message = "*Please provide your password")
#Transient
private String password;
#Column(name = "active")
private int active;
#ManyToMany()
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
//Plus getters-setters
}
Try passing name with referencedColumnName with #JoinColumn annotation. It worked for me.
#ManyToOne(optional = false)
#JoinColumn(name = "userTypeId", referencedColumnName = "id",nullable = false)
private UserType userType;
My entities were User and UserType where User have an attribute "userTypeId" as the foreign key.

org.postgresql.util.PSQLException: ERROR: null value in column "category_id" violates not-null constraint

i have a weird issue : i'am trying to save a User in my DB, this user has a list of skills. those skills are already in the db with linked categories and categories have linked domains. the structure looks like this :
when i print the list of skills from the applicant i have this :
skills=[Skill{categories=[Category{domains=[Domain{id=4, name=DevOps}], id=13, name=BackEnd}], id=23, name=Java}, Skill{categories=[Category{domains=[Domain{id=4, name=DevOps}], id=13, name=BackEnd}], id=24, name=C}],
and here is the table making the link between Applicant and skills :
but when i'm trying to save the applicant i have this Détail : Failing row contains (23, null, null, 499). can someone explain me ? I'm working on a spring application using jpa annotaions.
EDIT 1 :
ApplicantEntity :
#Entity
#Table(name = "ATS_APPLICANT")
public class ApplicantEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "home", unique = false, nullable = true)
private Boolean home;
#Column(name = "anonymous", unique = false, nullable = true)
private Boolean anonymous;
#Enumerated(EnumType.STRING)
#Column(name = "job_type")
private JobType jobType;
#Column(name = "min_salary", unique = false, nullable = true)
private Integer minSalary;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(unique = true)
private UserEntity user;
#OneToMany(targetEntity = ApplicantWorkExperienceEntity.class, cascade = CascadeType.ALL)
private List<ApplicantWorkExperienceEntity> applicantWorkExperiences = new ArrayList<ApplicantWorkExperienceEntity>();
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
#JoinTable(name = "ATS_APPLICANT_SKILL", joinColumns = #JoinColumn(name = "applicant_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "skill_id", referencedColumnName = "id"))
private List<SkillEntity> skills = new ArrayList<SkillEntity>();
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "ATS_APPLICANT_LOCATION", joinColumns = #JoinColumn(name = "applicant_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "location_id", referencedColumnName = "id"))
private List<LocationEntity> locations = new ArrayList<LocationEntity>();
SkillEntity :
#Entity
#Table(name = "ATS_SKILL")
public class SkillEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(min = 1, max = 42)
#Column(name = "name", length = 42, nullable = false, unique = true)
private String name;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "ATS_SKILL_CATEGORY", joinColumns = #JoinColumn(name = "skill_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "category_id", referencedColumnName = "id"))
private List<CategoryEntity> categories = new ArrayList<CategoryEntity>();
CategoryEntity :
#Entity
#Table(name = "ATS_CATEGORY")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(min = 1, max = 42)
#Column(name = "name", length = 42, nullable = false, unique = true)
private String name;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "ATS_CATEGORY_DOMAIN", joinColumns = #JoinColumn(name = "category_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "domain_id", referencedColumnName = "id"))
private List<DomainEntity> domains = new ArrayList<DomainEntity>();
EDIT 2 :
DomainEntity :
#Entity
#Table(name = "ATS_DOMAIN")
public class DomainEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(min = 1, max = 42)
#Column(name = "name", length = 42, nullable = false, unique = true)
private String name;
I succeed by using #ElementCollection annotation on skills.

Hibernate Many To one 3 table involved

I'm starting with hibernate and I having some difficulties to build a easy
relationship of tables
, hibernate throw nested exception is org.hibernate.MappingException: Unable to find column with logical name: USERNAME in org.hibernate.mapping.Table(USER_FILESYSTEM) and its related supertables and secondary tables
I have this model
USER--1---N-->USER_FILE_SYSTEM--1--N-->USER_FS_THUMBS
All column name on DB squema are OK the column username" exists on table USER_FILESYSTEM
and table user
Table Users
#Entity
#Table(name = "USERS")
public class Users implements Serializable {
#Id
#Column(name = "USERNAME", nullable = false, length = 15)
private String username;
#Column(name = "PASSWORD", nullable = false, length = 64)
private String password;
#Column(name = "FIRSTNAME", length = 32)
private String firstname;
#Column(name = "LASTNAME", length = 32)
private String lastname;
#Column(name = "EMAIL", nullable = false, length = 60)
private String email;
#Column(name = "TELEPHONE", length = 50)
private String telephone;
#OneToOne(cascade = CascadeType.ALL)
#JoinTable(name = "USER_ROLE",
joinColumns = {
#JoinColumn(name = "USERNAME_ID", referencedColumnName = "USERNAME")},
inverseJoinColumns = {
#JoinColumn(name = "ROL_ID", referencedColumnName = "ROL")}
)
private Rol role;
#OneToMany(
fetch = FetchType.EAGER, mappedBy = "username"
)
private Set<UserFileSystem> fileSystem;
Table UserFileSystem
#Entity
#Table(name = "USER_FILESYSTEM")
public class UserFileSystem implements Serializable {
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USERNAME", nullable = false)
private Users username;
#Id
#Column(name = "SERVICE_ID", nullable = false, length = 10)
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer serviceId;
#Id
#Column(name = "SERVICE_FOLDER", nullable = false, length = 64)
private String serviceFolder;
#Column(name = "PROTOCOL", length = 20)
private String protocol;
#Column(name = "PARAMS", length = 512)
private String params;
#OneToMany(
fetch = FetchType.LAZY, mappedBy = "userFileSystemThumbsPK"
)
private Set<UserFileSystemThumbs> fileSystemThumbs;
Table UserFileSystemThumbs
#Entity
#Table(name = "USER_FS_THUMBS")
public class UserFileSystemThumbs implements Serializable {
#EmbeddedId
private UserFileSystemThumbsPK userFileSystemThumbsPK;
#Column(name = "SERVICE_URL", nullable = false)
private String serviceUrl;
#Column(name = "CONTENT", nullable = false)
private byte[] content;
#Column(name = "MIME_TYPE", nullable = false)
private String mimeType;
Primary key entity UserFileSystemThumbs
#Embeddable
public class UserFileSystemThumbsPK implements Serializable {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "USERNAME", nullable = false, referencedColumnName = "USERNAME"),
#JoinColumn(name = "SERVICE_ID", nullable = false, referencedColumnName = "SERVICE_ID")
})
private UserFileSystem userFileSystem;
#Column(name = "SERVICE_URL_HASH", nullable = false)
private String serviceUrlHash;
Constructor equals hash....
the problem I think that UserFileSystemThumbsPK USERNAME column do reference to UserFileSystem but in this table the column USERNAME is provided by users.
Solution by OP.
I changed
#Entity
#Table(name = "USER_FILESYSTEM")
public class UserFileSystem implements Serializable {
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USERNAME", nullable = false)
private Users username;
#Id
#Column(name = "SERVICE_ID", nullable = false, length = 10)
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer serviceId;
}
for this
#Entity
#Table(name = "USER_FILESYSTEM")
public class UserFileSystem implements Serializable {
#EmbeddedId
private UserFileSystemID userFSID;
}
and I created the object UserFileSystemID with 2 values of PK
It's working like a champ!

Categories