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

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 ?

Related

Custom ConstraintValidator not invoked before persist

#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.

Micronaut - not possible to use PersistenceContext

I'am new to micronaut and I try to follow this little project. However I would like it to work with postgres.
My application.yml looks like this:
micronaut:
application:
name: hello-world
datasources:
default:
url: 'jdbc:postgresql://localhost:5432/test'
username: test
password: test
driver-class-name: org.postgresql.Driver
jpa:
default:
properties:
hibernate:
hbm2ddl:
auto: update
show_sql: true
I have access to the database via intellij.
In the pom.xml I have the following dependencies:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.micronaut.configuration</groupId>
<artifactId>micronaut-jdbc-hikari</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.micronaut.configuration</groupId>
<artifactId>micronaut-hibernate-jpa</artifactId>
</dependency>
Additionally it is mentioned in the link that one needs annotionProcessor, so I added this to my build profile:
<annotationProcessorPaths>
<path>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</path>
</annotationProcessorPaths>
So now everytime I try to do the following:
#PersistenceContext
private EntityManager entityManager;
I get the following error:
Caused by: io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [javax.persistence.EntityManager] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
However I already have annotation processing enabled. And I also have a #Entity-class:
#Entity
#Table(name = "users")
public class User {
#NotBlank
#Column(name = "name")
private String userName;
public User() {
}
public User(#NotBlank final String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(final String userName) {
this.userName = userName;
}
}
What exactly am I missing in my setup?
There were multiple issues with my setup.
datasource and jpa need to be at root level
The #Entity needs a #Id
So in the end the application.yml looks like this:
micronaut:
application:
name: hello-world
datasources:
default:
url: 'jdbc:postgresql://localhost:5432/test'
username: test
password: test
driver-class-name: org.postgresql.Driver
jpa:
default:
packages-to-scan:
- 'test'
properties:
hibernate:
hbm2ddl:
auto: update
show_sql: true
And the #Entity-Class needs an #Id-Attribute:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Column(name = "user_name")
private String userName;
public User() {
}
public User(#NotBlank final String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(final String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
'}';
}
}

Why is a field of my entity class null?

I have these two entities in a one to many relation:
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Short id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
private Collection<Product> productCollection;
...
#XmlTransient
public Collection<Product> getProductCollection() {
return productCollection;
}
...
and
public class Product implements Serializable {
...
#JoinColumn(name = "category_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Category categoryId;
...
generated with NetBeans. The problem is that when the method getProductCollection() is called by the ControllerServlet the Collection of Product is null.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
Category selectedCategory;
Collection<Product> categoryProducts;
// if category page is requested
if (userPath.equals("/category")) {
// get categoryId from request
String categoryId = request.getQueryString();
if (categoryId != null) {
// get selected category
selectedCategory = categoryFacade.find(Short.parseShort(categoryId));
// place selected category in request scope
request.setAttribute("selectedCategory", selectedCategory);
// get all products for selected category
categoryProducts = selectedCategory.getProductCollection();
// place category products in request scope
request.setAttribute("categoryProducts", categoryProducts);
}
Notice the null value of productCollection when other fields has been yet initialized
Edit 1: I declared the categoryFacade in the ControllerServlet applying the #EJB annotation
public class ControllerServlet extends HttpServlet {
#EJB
private CategoryFacade categoryFacade;
Edit 2: Here is the persistence.xml document
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="AffableBeanPU" transaction-type="JTA">
<jta-data-source>jdbc/affablebean</jta-data-source>
<properties/>
</persistence-unit>
</persistence>
Edit 3: I'm using TomEE 7.0.2
Try to initialize the Collection empty like:
#OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
private Collection<Product> productCollection = new HashSet<>();
Then you won't have null values even when there are no results in the lazy loaded relationship. If there are loaded values, they will be added to the collection.

JPA entity returns null while database is not empty

I am developing a Java web application with I am using netbeans 8 as IDE and glassfissh as the server I am trying to fetch data from Users table in the database I need to use JPA as data model layer for this purpose,
edited
although the Entity is generated by netbeans from a table in the MySQL database which has some rows the resultList which is returned from the executing the query returns no rows from a table in Derby database and it is empty
in the following I provided my Entity Java bean code which is automatically generated by netbeans IDE
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Home
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findById", query = "SELECT u FROM Users u WHERE u.id = :id"),
#NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name = :name"),
#NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email"),
#NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"),
#NamedQuery(name = "Users.findByRememberToken", query = "SELECT u FROM Users u WHERE u.rememberToken = :rememberToken"),
#NamedQuery(name = "Users.findByCreatedAt", query = "SELECT u FROM Users u WHERE u.createdAt = :createdAt"),
#NamedQuery(name = "Users.findByUpdatedAt", query = "SELECT u FROM Users u WHERE u.updatedAt = :updatedAt")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "name")
private String name;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "email")
private String email;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "password")
private String password;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "remember_token")
private String rememberToken;
#Basic(optional = false)
#NotNull
#Column(name = "created_at")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Basic(optional = false)
#NotNull
#Column(name = "updated_At")
#Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
public Users() {
}
public Users(Integer id) {
this.id = id;
}
public Users(Integer id, String name, String email, String password, String rememberToken, Date createdAt, Date updatedAt) {
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.rememberToken = rememberToken;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRememberToken() {
return rememberToken;
}
public void setRememberToken(String rememberToken) {
this.rememberToken = rememberToken;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Users)) {
return false;
}
Users other = (Users) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "some string";
}
}
and this is my Servlet code where I try to get the Users of database
#PersistenceUnit
EntityManagerFactory emf;
emf.createEntityManager().createNamedQuery("Users.findAll").getResultList().size()
but the ResultList did not fetch any data from database
this is the log from the server which shows iit is connected to Derby
Config: Connected: jdbc:derby://localhost:1527/sun-appserv-samples;;create=true
User: APP
Database: Apache Derby Version: 10.10.1.3 - (1557168)
Driver: Apache Derby Network Client JDBC Driver Version: 10.10.2.0 - (1582446)
edited
whil based on configuration I think it is supposed to connect to MySQL this is my glassfish-resources.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false"
connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10"
connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit"
datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false"
idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true"
lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false"
max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_mysql_rootPool"
non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource"
statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0"
wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="mydatabase"/>
<property name="User" value="root"/>
<property name="Password" value=""/>
<property name="URL" value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="realestateConnection" object-type="user" pool-name="mysql_mysql_rootPool"/>
</resources>
and this is my persistence.xml file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="architectsPU" transaction-type="JTA">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
edited
please help me how to solve this issue and how can change the config in order to get connected to the right database when deploying the file that tells server which data source to connect is it same as `persistence.xml? and if not where is it located?
As the comments on the question state clearly enough, your JPA provider is using Apache Derby for database rather than what you wanted (mySQL). This is because your persistence.xml doesn't bother specifying what datasource(s) to use. You need to specify jtaDataSource (and maybe also nonJtaDataSource) to point to your JTA MySQL DataSource so then the JPA provider has the information it needs to use your DataSource.

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.