Custom ConstraintValidator not invoked before persist - jpa

#Target({TYPE, ANNOTATION_TYPE, FIELD})
#Retention(RUNTIME)
#Constraint(validatedBy = {UniqueNameValidator.class})
#Documented
public #interface UniqueName {
String message() default "Unique name constraint";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class UniqueNameValidator implements ConstraintValidator<UniqueName, Object> {
#Override
public void initialize(UniqueName constraintAnnotation) {
System.out.println("UniqueNameValidator -> initialize() method invoked!");
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
System.out.println("UniqueNameValidator -> isValid method invoked!");
return true;
}
}
#Entity
public class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#UniqueName
#Column(name = "NAME")
private String name;
//Getters & Setters
}
The dependencies used in my project are :
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.6.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
Env :
Java 8
WebLogic Server: 12.2.1.2.0
Eclipselink version 2.6.4
After trying many suggestions from SOF i can't figure out why my custom validator is not called before persisting the entity (Validation on class level or field level) !
Any help will be appreciated.

Related

SpringBoot connect to MongoDB

I am learning on Spring boot to insert data into MongoDB and encountered some issues. Please give me some of your advise, thank you.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>com.onboard.proj</groupId>
<artifactId>onboard</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
UserController.java
#RestController
public class UserController {
#Autowired
MongoService db;
#PostMapping("/create")
public User createNew(#RequestParam("name") String name, #RequestParam("role") String role){
User obj = new User(name, role);
User newObj = db.save(obj);
return newObj;
}
}
MongoService.java
#Service
public class MongoService {
#Autowired
MongoRepository repo;
public User save(User u) {
return repo.save(u);
}
}
MongoRepository.java
public class MongoRepository {
#Autowired
private MongoTemplate template;
public User save(User e) {
if(e != null) {
template.insert(e);
}
return e;
}
}
User.java
#Document
public class User {
#Id
private String id;
//#Field("name")
private String name;
//#Field("role")
private String role;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getRole() {
return role;
}
public void setName(String name) {
this.name = name;
}
public void setRole(String role) {
this.role = role;
}
public User(String name, String role) {
super();
this.name = name;
this.role = role;
}
public User() {
super();
}
}
I tried to use PostMan and did the following setting, but couldnt reach the UserController. The result from Postman is always 404, NOT FOUND.
Add the annotation #RequestMapping("/") also on class level since Spring requires a mapping for your class also, not only the method.
#RestController
#RequestMapping("/")
public class UserController {
Also you have
#RequestParam("name") String name, #RequestParam("role") String role
but in Postman you pass name and role in JSON body. It is not coded to work like this. You should pass name and role as query parameters in Postman.
#RestController
#RequestMapping("/")
public class UserController {
#Autowired
MongoService db;
#PostMapping("/create")
public User createNew(#RequestParam("name") String name, #RequestParam("role") String role){
User obj = new User(name, role);
User newObj = db.save(obj);
return newObj;
}
}
it is better to use swagger you can get endpoints easily.

Spring Data JPA Primary Key Violation Constraint Not Working

Code and Configuration :
DB used - H2 in Memory database
User Entity :
#Entity
#Table(name = "users")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 455202739064202185L;
#Id // please note is not auto generated but manually generated
#Column(name = "id",unique=true)
#NotNull
private long id;
#Column(name = "firstName")
#NotEmpty(message = "First name is required")
private String firstName;
#Column(name = "lastName")
#NotEmpty(message = "Last name is required")
private String lastName;
#Column(name = "email")
#NotEmpty(message = "Email is required")
#Email(message="Email Must be well formed")
private String email;
}
UserRepository :
public interface UserJpaRepository extends JpaRepository<User, Long> {
}
UserServiceImpl :
this.userJpaRepository.saveAll(users);
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.exostar</groupId>
<artifactId>FileUpload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>FileUpload</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
</project>
Issue :
As per the User entity class , #Id is manually generated.
(I have a CSV file which has Id field which is read in User entity)
So Id is not auto generated
Whenever I call this.userJpaRepository.saveAll(users) and even when there is an User entity with Id already existing , the User entity gets overwritten.
That is , Id with same entity gets overwritten with new data.
It has to throw - Unique index or primary key violation error
However, when I try to insert duplicate entry into H2 database MANUALLY , it throws exception - Unique index or primary key violation
I also tried adding unique=true to Id field in User Entity but its not working
Can anybody please help on resolving this issue please ?
Well as it turns out that the behavior that you are seeing is because of the call to em.merge(...) in the save() implementation. Here is what actually happens:
#Transactional
#Override
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Entity must not be null.");
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity); // Update if the entity is not new
}
}
This is a sample code from SimpleJpaRepository implementation. you can use your own query methods for updating the existing query something like this:
#Modifying
#Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);

How to fix Spring Boot Postgres error: syntax error at or near: ")" Position: 209

I've got some trouble attempting to rebuild connection with Postgres server using Spring Boot (in Eclipse environment). Case-relevant entities look like:
1 - Specialization - web application I'm working provides with online registration for college athlete courses, so Specialization means gymnastics or sports any student can apply for upon his/her pleasure:
#Entity
#Table(name = "Specializations")
#Getter #Setter #NoArgsConstructor
public class Specialization {
#Id
#SequenceGenerator(name = "specialization_id_sequence", sequenceName = "specialization_id_sequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "specialization_id_sequence")
#Column(name = "id")
private Short id;
#Column(name="name")
private String name;
#ManyToOne
#JoinColumn(name="health_category_id", referencedColumnName = "id")
private HealthCategory category;
#Column(name="photo_file_path")
private String photoFilePath;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "specialization", cascade = CascadeType.ALL)
List <Trainer> trainerList;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "specialization", cascade = CascadeType.ALL)
List <Group> groupList;
//some hashCode() and equals() stuff here
#Override
public String toString() {
return "Specialization [id=" + id + ", name=" + name + ", min. approvable health category=" +
category.getId() + ", path=" + photoFilePath + "]";
}
2 - HealthCategory - prerequisite health class to be confirmed formally for getting admission to specialization-related engagement (different specilializations may be featured by the same health category required)
#Entity
#Table(name = "Health_categories")
#Getter #Setter #NoArgsConstructor
public class HealthCategory {
#Id
#SequenceGenerator(name = "category_id_sequence", sequenceName = "category_id_sequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "category_id_sequence")
#Column(name = "id")
private Short id;
#Column(name="name")
private String name;
#Column(name="state")
private Short state;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
private List <Specialization> specialization;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#Column(name="last_update")
private Date last_update;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
private List <User> userList;
#Override
public String toString() {
return "Health category [id=" + id + ", name=" + name + ", state=" + state + ", last update on=" + last_update + "]";
}
3 - Group - specialization-related group a student sign in to pass the course
#Entity
#Table(name = "Groups")
#Getter #Setter #NoArgsConstructor
public class Group {
#Id
#SequenceGenerator(name = "groupIdSequence", sequenceName = "groupIdSequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "groupIdSequence")
#Column(name = "group_id")
private Long group_id;
// eventual values: "open", "close"
#Column(name="registration_status")
private String registrationStatus;
// admission quota
#Column(name="target_size")
private Integer targetSize;
// real group size evaluation at the moment
#Column(name="actual_size")
private Integer actualSize;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group", cascade = CascadeType.ALL)
private List <User> userList;
#ManyToOne
#JoinColumn(name="group_specialization_id", referencedColumnName = "id", nullable = false, unique = true)
private Specialization specialization;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name="schedules",
joinColumns = { #JoinColumn(name = "group_id") },
inverseJoinColumns = { #JoinColumn(name="schedule_id", nullable = false) })
private List<GroupSchedule> scheduleList;
#ManyToMany(mappedBy = "groupList")
private List<Trainer> trainerList;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name="locations",
joinColumns = { #JoinColumn(name = "group_id", nullable = false) },
inverseJoinColumns = { #JoinColumn(name="location_id", nullable = false) })
private List<Location> locationList;
#Column(name="description")
private String desciption;
4 - Trainer - an instructor concerned of holding lessons for respective groups of student who take specific course:
#Entity
#Table(name = "Trainers")
#Getter #Setter #NoArgsConstructor
public class Trainer {
#Id
#SequenceGenerator(name = "trainerIdSequence", sequenceName = "trainerIdSequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "trainerIdSequence")
#Column(name = "trainer_id")
private Short trainer_id;
#Column(name="first_name")
private String firstName;
#Column(name="second_name")
private String secondName;
#Column(name="last_name)")
private String lastName;
#Column(name="photo_file_path")
private String photoFilePath;
#ManyToOne
#JoinColumn(name="specialization_id", referencedColumnName = "id", nullable = false, unique = true)
private Specialization specialization;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(
name="groups",
joinColumns = { #JoinColumn(name = "trainer_id", nullable = false) },
inverseJoinColumns = { #JoinColumn(name="group_id", nullable = false) })
private List<Group> groupList;
Because of difficulties when running code with Specialization objects, SpecializationService to be posted here:
#Service
public class SpecializationService {
#Autowired
private SpecializationRepository specializationRepository;
public SpecializationService(SpecializationRepository specializationRepository) {
this.specializationRepository = specializationRepository;
}
public void createSpecialization(Specialization specialization) {
specializationRepository.save(specialization);
}
public List<Specialization> findALL() {
return (List<Specialization>) specializationRepository.findAll();
}
public List<Specialization> getSpecializations() {
List<Specialization> specializations = new ArrayList<>();
specializationRepository.findAll().forEach(specializations::add);
return specializations;
}
}
SpecializationController code:
#RestController
public class SpecializationController {
#Autowired
SpecializationService specializationService;
#RequestMapping("/specialization")
public List<Specialization> getSpecializations() {
return specializationService.getSpecializations();
}
#RequestMapping(method = RequestMethod.POST, value = "/specialization/create")
public void createSpecialization(#RequestBody Specialization spec) {
specializationService.createSpecialization(spec);
}
}
Additively, there is relevant sql create table stuff:
CREATE SEQUENCE category_id_sequence;
CREATE TABLE Health_Categories (
id SMALLINT NOT NULL DEFAULT nextval('category_id_sequence') PRIMARY KEY,
name VARCHAR(30) DEFAULT NULL,
state SMALLINT NOT NULL,
last_update TIMESTAMP
);
-- Specialization --
CREATE SEQUENCE specialization_id_sequence;
CREATE TABLE Specializations (
id SMALLINT NOT NULL DEFAULT nextval('specialization_id_sequence') PRIMARY KEY,
name VARCHAR(50) DEFAULT NULL,
health_category_id SMALLINT REFERENCES health_categories (id),
photo_file_path VARCHAR(50) DEFAULT NULL,
CONSTRAINT specialization_ibfk_1 FOREIGN KEY (id) REFERENCES health_categories (id)
);
Once executing #SpringBootApplication class as follows:
#SpringBootApplication
public class DatabaseComponentsApplication {
#Autowired
private HealthCategoryService categoryService;
#Autowired
private SpecializationService specializationService;
public static void main(String[] args) {
SpringApplication.run(DatabaseComponentsApplication.class, args);
}
#EventListener(ApplicationReadyEvent.class)
private void testJpaMethods() {
HealthCategory cat2 = new HealthCategory();
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
cat2.setLast_update(ts);
cat2.setName("Test2");
cat2.setSpecialization(null);
cat2.setState((short) 8);
categoryService.createCategory(cat2);
Specialization spec = new Specialization();
spec.setCategory(cat2);
spec.setName("Soccer");
spec.setPhotoFilePath(null);
specializationService.createSpecialization(spec);
specializationService.getSpecializations().forEach(it -> System.out.println(it));
}
}
it complains due to wrongness I still can't figure out to manage:
Caused by: org.postgresql.util.PSQLException: error: syntax error at or near: ")" Position: 209
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2505) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2241) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:158) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:108) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
... 74 common frames omitted
Could you share your ideas what syntax issue causes that?
EDITED: pom.xml code as follows
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>databaseComponents</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>databaseComponents</name>
<description>DAO implementation draft </description>
<properties>
<java.version>1.8</java.version>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Also, application.properties stuff:
spring.datasource.driver=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/core_database
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.main.web-application-type=none
Is there any problem with calling findAll() method.
public List<Specialization> findAll() {
return (List<Specialization>) specializationRepository.findAll();
}
Can you replace getSpecializations() method
specializationService.getSpecializations().forEach(it -> System.out.println(it));
with findALL() method
specializationService.findALL().forEach(it -> System.out.println(it));
and see if it works ?

#query annotation doesn't work with hibernate-ogm and mongodb in spring boot

I wrote a Spring boot,hibernate orm application using mysql database.... But now I want to switch to mongodb... I used Hibernate-ogm for fulfill my requirement. When run the application the console shows successfully switch to mongodb using hibernate-ogm... But the query is not working... I import below packages for my repository to hibernate-orm and these imports works fine with mysql... But in hibernate-ogm #query annotation doesn't work...
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.Query;
This is my model
#Entity
#Indexed
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String nic;
private String emp;
private String firstName;
private String lastName;
#NotEmpty
private String mobile;
private String email;
private String status;
private String agency;
#NotEmpty
#Column(unique = true)
private String userName;
#NotEmpty
private String password;
private String userIDandTime;
private String recentUpdateBy;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_roles",
joinColumns = {
#JoinColumn(name = "id")},
inverseJoinColumns = {
#JoinColumn(name = "roleId")})
private Set<Role> userRoles;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_units",
joinColumns = {
#JoinColumn(name = "id")},
inverseJoinColumns = {
#JoinColumn(name = "unitId")})
private Set<Unit> userUnits;
}
This is my full repository
package lk.tradeportal.repository;
import lk.tradeportal.domain.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
/**
* Created by Ignotus on 1/28/2017.
*/
public interface UserRepository extends CrudRepository<User, Long> {
#Override
User save(User user);
#Override
User findOne(Long id);
#Query("select u from User u where u.userName!='super#allSLSI'")
List<User> findAll();
#Query("select u from User u where u.agency = :agency and u.firstName !='admin'")
List<User> findAllStaffUsersByOGA(#Param("agency") String agency);
#Query("select u from User u where u.nic='N/A' and u.firstName='N/A' and u.email='N/A'")
List<User> profileNotCompletedUsers();
#Query("select u from User u where u.agency!='SLSI'")
List<User> chafindAll();
#Query("select u from User u where u.userName = :userName")
User getUserByLoginUserName(#Param("userName") String userName);
#Query("select u from User u where u.id = :userId")
User getUserByUserId(#Param("userId") Long userId);
#Query("select u.email from User u where u.agency !='SLSI'")
List<User> getEmails();
#Query("select a from User a where a.nic = :nic")
User getAgentByNIC(#Param("nic") String nic);
#Override
void delete(Long id);
#Override
void delete(User user);
}
This is my Service class
package lk.tradeportal.services;
import java.text.SimpleDateFormat;
import java.util.Date;
import lk.tradeportal.domain.Role;
import lk.tradeportal.domain.User;
import lk.tradeportal.repository.RoleRepository;
import lk.tradeportal.repository.UserRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import lk.tradeportal.domain.Unit;
import lk.tradeportal.repository.UnitRepository;
import lk.tradeportal.security.domain.AuthenticatedUser;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Created by ignotus on 1/31/2017.
*/
#Service
public class UserServices {
private static final Logger serviceLogger = LogManager.getLogger(UserServices.class);
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private UnitRepository unitRepository;
#Autowired
private UserServices UserService;
public User getUserFromUserId(Long id) {
return userRepository.getUserByUserId(id);
}
public List<User> getAllUsers() {
Runtime.getRuntime().gc();
return userRepository.findAll();
}
public User getUserByLoginUserName(String userName) {
return userRepository.getUserByLoginUserName(userName);
}
public List<User> findAllStaffUsersByOGA(String agency) {
return userRepository.findAllStaffUsersByOGA(agency);
}
public List<User> profileNotCompletedUsers() {
return userRepository.profileNotCompletedUsers();
}
public List<User> getChaAllUsers() {
System.out.println(userRepository.chafindAll());
return userRepository.chafindAll();
}
public List<Role> getAllRoles() {
return roleRepository.findAll();
}
public List<Role> findTraderRoles() {
return roleRepository.findTraderRoles();
}
public List<Role> findMOIC() {
return roleRepository.findMOIC();
}
public List<Role> SuperADMINRoles() {
return roleRepository.SuperADMINRoles();
}
public List<Unit> getAllUnits() {
return unitRepository.findAll();
}
public void deleteUserById(String id) {
User user = userRepository.findOne(Long.valueOf(id));
userRepository.delete(user);
}
public User getAgentByNIC(String nic) {
return userRepository.getAgentByNIC(nic);
}
}
This is my application config.
package lk.tradeportal;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by ignotus on 1/22/2017.
*/
#Configuration
#ComponentScan(basePackages = "lk.tradeportal")
#EnableWebMvc
#ImportResource(locations = "classpath:tradeportal-servlet-config.xml")
#EnableJpaRepositories(basePackages="lk.tradeportal.repository")
#EnableTransactionManagement
public class TRADEPORTALStarter extends SpringBootServletInitializer {
private static final Logger slsiLogger = LogManager.getLogger(TRADEPORTALStarter.class);
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
slsiLogger.info("Starting application");
SpringApplication application = new SpringApplication(TRADEPORTALStarter.class);
context = application.run(args);
application.setRegisterShutdownHook(true);
}
#PreDestroy
private static void closeAppContext(){
context.close();
}
#Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(TRADEPORTALStarter.class);
}
}
This is my persistence.xml
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="ogm-jpa-tutorial" transaction-type="RESOURCE_LOCAL">
<!-- Use Hibernate OGM provider: configuration will be transparent -->
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<class>lk.tradeportal</class>
<properties>
<property name="hibernate.ogm.datastore.provider" value="mongodb" />
<!--<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform" />-->
<property name="hibernate.ogm.datastore.create_database" value="true"/>
<property name="hibernate.ogm.datastore.database" value="trade_portal_db"/>
</properties>
</persistence-unit>
</persistence>
My dependencies are
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!--handle servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--<Email Dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<!--jasper-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>3.7.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web-services -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.ws.security/wss4j -->
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-libs -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-libs</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
<version>2.2.0.RELEASE</version>
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-mongodb</artifactId>
<version>5.1.0.Final</version>
<exclusions>
<exclusion>
<groupId>org.hibernate.hql</groupId>
<artifactId>hibernate-hql-parser</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.ogm/hibernate-ogm-core -->
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-search-orm -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.6.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-search-engine -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.6.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.hql</groupId>
<artifactId>hibernate-hql-parser</artifactId>
<version>1.4.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
What is the error in #query annotation. How I get I data from my database.. Please help me.

Annotations Hibernate 3.5

The below annotation works when applying it to the field:
#OneToMany(targetEntity=TestMany.class,
cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="TESTID")
private Set<TestMany> testManys = new HashSet<TestMany>();
But fails when I place it above the getter below:
public Set<TestMany> getTestManys() {
return testManys;
}
With the following error:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: TEST, for columns: [org.hibernate.mapping.Column(testManys)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:291)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:275)
at org.hibernate.mapping.Property.isValid(Property.java:217)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:464)
at org.hibernate.mapping.RootClass.validate(RootClass.java:236)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1193)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1378)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:860)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:779)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 47 more
The Many side of the relationship:
#SuppressWarnings("serial")
#Entity
#Table(name="TESTMANY")
public class TestMany extends BaseEntityImpl{
#ManyToOne
#JoinColumn(name="TESTID", insertable=false, updatable=false)
private Test test;
I don't know why it works on the property but not on the getter and it's driving me nuts. The tables are fine and the annotation seems fine to me. Am I missing something very obvious? Could it be a version problem?
There is a basic base class but i dont think this has anything to do with it:
#MappedSuperclass
public abstract class BaseEntityImpl implements BaseEntity, Serializable {
private static final long serialVersionUID = 7887314289537012320L;
#Id #GeneratedValue(strategy = AUTO)
#Column(name = "ID")
private Long id;
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
}
I am using version 3.5.3-Final and 3.2.0.Final for the hibernate-coomons-annotations.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.3-Final version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.3-Final <version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
Does anyone have any ideas or experienced something similar? I've spent 2.5 hours of my life trying to fix this one and I predict another 12.
I'm unable to test the solution right now (I'm unfortunately stuck with a computer with less than a quadrillion gigabytes of RAM, so no Hibernate launching here), but as the doc demonstrates, your set needs a type, so instead of:
#OneToMany(targetEntity=TestMany.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="TESTID")
private Set testManys = new HashSet();
you use:
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="TESTID")
private Set<TestMany> testManys = new HashSet();
and it should do the trick. In case you don't like the Hibernate documentation, you might enjoy reading this.