Questions tagged [jpa]
19348 questions
0
votes
2
answer
21
Views
JPA: How to map only one property from another entity
Let's say I have two entities:
@Entity
public class Phone {
@Id
private Long id;
private String number;
}
@Entity
public class Person {
@Id
private Long id;
private String name;
}
The relationship between a person and a phone is one to one.
How could I access only the phone's number in the Person en...
1
votes
1
answer
2k
Views
Unable find Entity .. while trying to save data
I'm getting this exception when I try to save a topic with a message:
nested exception is javax.persistence.EntityNotFoundException: Unable to find mypackage.model.Message with id fb8d39ea-0094-410d-975a-ea4495781422
Here is the model :
@Entity
public class Topic {
@Id
private String id;
private St...
1
votes
1
answer
684
Views
Test Spring Data Repository in a project without a Spring Boot Application main class
I have a small project that does not contain a class to run a Spring Boot Application. In that class I only have some configuration and some repositories. I would like to test those repositories inside the small project.
For that, I have the following:
@SpringBootTest
@DataJpaTest
public class TaskR...
1
votes
2
answer
2k
Views
how to do a JOIN FETCH in jpa criteria
I am trying to translate the query below to criteria api.
SELECT er from ereturn er JOIN FETCH product_item pi ON pi.ereturn_id = er.id WHERE pi.status = 'RECEIVED'
To something like this:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery criteria = builder.createQuery( Ereturn.class...
1
votes
1
answer
680
Views
Does JPA return “null” or empty collection for a collection property that is empty in the DB?
If I have a JPA entity containing a collection field, such as
public class Post {
// [...]
@OneToMany
private List tags;
the corresponding database schema will typically contain a separate table for storing the tags, where each record contains one tag and a foreign key reference to the 'Post' ta...
1
votes
3
answer
185
Views
How to insert 780k records Spring Data Postgres
CSV file will be uploaded in Amazon S3 bucket.
Current Implementation:
Reading CSV file using OpenCSV utility's readAll which returns List
Map every column value to an entity object
Create a List object (Current Size :: 15000)
Invoke Spring Data CRUD Repository saveAll(List objects)
Out of 780k reco...
1
votes
1
answer
1.3k
Views
Spring Data JPA method query with paging gives me an error
I am developing with Spring Data Jpa. I have an interface extending JpaRepository, and I want to query with Query Method and paging.
I want to query 'select * from cheat where vote
1
votes
1
answer
53
Views
Spring boot: error asking to implement all methods in JpaRepository
Why is this happening? It didn't happen when I worked on a spring project in STS few months back.
I have imported the following in the class:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
Following is my pom.xml:
4.0.0
org.springframe...
1
votes
5
answer
160
Views
Spring Boot + JPA : @Transactional annotation : Roll back is not working
I am using @Transactional with spring boot and jpa. But it is not working. Can somebody help out.
My inserts are in myDAO which is autowired in service class. Below code is method of service class which is implementing service interface
class MyService implements Service {
@Transactional(rollbackFor...
0
votes
1
answer
14
Views
How to use method parameter as a plain text in @Query annotation
In a JPA repository, I need to do a native query, and in this native query, I need to be able to sort by a column. I want the direction of this sort be determined by one of the parameter of this method.
Here is the code I want to write but doesn't work.
@Repository
interface StudentRepository extend...
1
votes
1
answer
35
Views
Does Spring Data JPA have any way to sum an entity column using method name resolving?
Spring Data JPA can sum colomn using specifications. But does it have any way to sum an entity column using method name resolving? Let's say I want a method sumCreditAmount to sum column with specific name, just like a method findByCreditAmount to fetch all entities with a specific creditAmount.
1
votes
3
answer
317
Views
Does Hibernate has a specific condition for naming columns that start with the same letter?
I'm using spring boot and jpa hibernate to create some tables in my database but it throws a weird exception which i don't really understand.
@Entity
public class Option {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String marca;
private String model;
private String a...
1
votes
1
answer
226
Views
ORM Who can generate script dynamically
So basically I was checking working of hibernate, as well evaluated ORMs JOOQ. JPA is main de-facto standard for all java based ORM implementations more or less.
I am not saying they are not perfect or good but my problem is like I have found many issues and hick-ups while using various options prov...
1
votes
1
answer
57
Views
Spring data, find by property of a nested object
I have the following code:
@Entity
public class StudentEntity {
@Id
private String id;
private Student student;
...
}
public class Student {
private String name;
private List grades;
}
public class Grade {
private String className;
private String grade;
}
I've set up a spring data mongodb repository...
1
votes
2
answer
90
Views
How to construct this join query with JPA API?
Two tables:
CREATE TABLE `foo` (
`foo_id` bigint(20) not null auto_increment,
`name` varchar(32) not null,
`_deleted_` tinyint(1) default '0',
PRIMARY KEY (`foo_id`)
) ;
CREATE TABLE `bar` (
`bar_id` bigint(20) not null auto_increment,
`foo_id` bigint(20) not null,
`key` varchar(32) not null,
`va...
1
votes
2
answer
43
Views
How to programmatically discover the JPA implementation and SQL dialect being used by Spring Boot?
I know it is possible to change the JPA implementation in use by Spring Boot, the default is to use Hibernate, but it's also possible to user others, like EclipseLink. It is possible to find, at application runtime, which JPA implementation is being used, and also discover which SQL dialect is curre...
1
votes
2
answer
36
Views
How to enable H2 Database Server Mode in Spring Boot
I'm using a H2 database with a file using Spring Boot.
In my application.properties, I have this entry:
spring.datasource.url=jdbc:h2:file:c:/Testprojekte/spring-boot-h2-db
But now I would like to be able to look at the database while running the application, which currently isn't possible because I...
0
votes
1
answer
34
Views
ArrayList with more 10 items saved not ordered to DB
I receive List dtos with 14 MyDto and try to save it to the database.
I receive List
loop dtos and on each step:
2.1 -> map MyDto to MyEntity
2.2) -> save and flush MyEntity to DB
I expect 14 rows in DB, saved in the order in which I saved. For example:
row0
row1
row2
row3
row4
row5
row6
row7
row8...
0
votes
1
answer
22
Views
JPA returning a nested object after creation - 500 Internal Server Error
I have my main object:
@Data
@Entity
@EqualsAndHashCode(callSuper = false)
@Table(name = MAIN_OBJ)
public class MainObj {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = 'MAIN_OBJ_ID', unique = true, nullable = false)
private Integer manObjId;
@ManyToOne
@JoinColumn(name = 'SUB_OB...
0
votes
0
answer
3
Views
Can I have two persistence.xml files in my spring maven project
Is it possible for me to have two different persistence.xml files under META-INF eg. persistence-one.xml and persistence-two.xml and then somehow use in my spring-context.xml to use the appropriate one using property files ?
I am doing this because I have two separate environments with different...
1
votes
1
answer
11
Views
How to make JPA @query work with projection that has another projection in it
I'm trying to get projections works on @query in JPA with joined columns as an another project as well.
Say, I have 2 entities: course and student and student can have many courses and the foreign key is on the course table:
student(id, name, email, age, grade, uuid)
course(id, name, uuid, student_i...
0
votes
0
answer
12
Views
Spring Data JPA BigList insert
I've been trying for two days now to store an array list with about six million entries in my Postgres database with Spring-Data-JPA.
The whole thing works, but it's very slow. I need about 27 minutes for everything.
I've already played around with the batch size, but that didn't bring much succes...
1
votes
2
answer
6.5k
Views
Convert SQL statement to JPQL statement
I wonder how I convert this SQL statement to JPQL:
SELECT sum(price) AS Income, count(*) AS Passages, Station.Name
FROM Passage
INNER JOIN station ON passage.stationId = station.id
GROUP BY Station.Name
wouldnt it be something like this:
SELECT sum(price) AS Income, count(p) AS Passages, s.Name FRO...
0
votes
0
answer
5
Views
Spring db config with 2 data sources - the second connection throws HibernateException
I'm working on a Spring project that requires 2 data sources. One is to save user details and the others are to save product's information and other processes.
I defined the database configuration as follow:
@Value('${caffein.datasource.url}')
private String APP_DB_URL;
@Value('${caffein.datasource....
0
votes
0
answer
19
Views
Can't find Eclipse (JPA 2.0) as a default library for my Persistence Unit in netbeans
I want to create a Persistence Unit in my netbeans IDE but i can't find Eclipse (JPA 2.0) as a default library, how do i make Eclipse (JPA 2.0) a default library? Thanks for your help in advance.
1
votes
3
answer
106
Views
SQL Error: 23503, SQLState: 23503 in SpringBoot 2.1.4.RELEASE app
I have a SpringBoot 2.1.4.RELEASE RESTful Web Service app., using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
I have this class:
@Entity
@Table(name='t_menu_alert_notification')
public class MenuAlertNotification implements Serializable {
/*...
0
votes
0
answer
5
Views
How do I create a lookup table in my application using JPA and Hibernate?
I have an application that uses JPA and Hibernate. I have an entity called Person that has several fields that I would like to use lookup tables for. For example, there is gender, which [I believe] should look like this:
@Entity
@Table(name = 'genderLookup')
@EntityListeners(AuditingEntityListener.c...
1
votes
2
answer
2.7k
Views
JPA Criteria query for one to many relation with predicate on child not working
I have a parent entity
@Entity
@Table(name = 'tblmodule', uniqueConstraints = {
@UniqueConstraint(columnNames = 'name')
})
@SequenceGenerator(name = ACLEntityConstant.SEQ_MODULE, initialValue = 1, allocationSize = 100)
public class Module implements BaseEntity {
private static final long serialVersi...
1
votes
3
answer
1k
Views
How do you programmatically generate a Hibernate JPA schema?
I'd like to use the Hibernate/HBM2DDL schema generation as a starting point for managing my application's SQL schema using a tool like Liquibase or Flyway. To assist with that, I need a small utility in my project that I can run that will print out the auto-generated schema.
With older versions or H...
1
votes
1
answer
721
Views
Query creation method gives error
My Entity has a field like
@Column(name = 'workflow_status', columnDefinition = 'nvarchar(255)')
private String workflow_status;
So in my Controller I want to fetch the entries by workflow_status, I wrote the Query method that JPA provides
List findByWorkflow_status(String workflow_status);
But thi...
1
votes
2
answer
2.2k
Views
How to use Spring security without password encoding?
I'm trying to learn Spring security currently. I used BCryptPasswordEncoder to encode user password before persisting into a database
Code:
@Override
public void saveUser(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setActive(1);
Role userRole = roleRepositor...
1
votes
2
answer
1k
Views
Trouble when changing Spring Boot version from 2.0.3.RELEASE to 2.1.0.M4
I have a working code that stops to work when I change Spring Boot version from 2.0.3.RELEASE to 2.1.0.M4
The error is:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
***************************
APPLICATION FAILED TO START
*********...
1
votes
3
answer
73
Views
Unindentified SQL error syntax with SpringBoot and JPA
The compilation of my SpringBoot app fails to create a database.
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'read bit, releaseDate date,
primary key (id)) engine=In...
1
votes
2
answer
313
Views
Validate schema programmatically using hibernate
In mose projects the way to run your java app with schema validation is with that configuration (when using spring):
spring.jpa.hibernate.ddl-auto=validate
I ran into a problem that I need to validate my schema at a specific times during running, is there any way to implement that?
I saw that hibern...
1
votes
4
answer
54
Views
Cannot get username in spring boot
The problem is: When I use JpaRepository and use a method to get user by username like the code below:
public interface UserRepository extends JpaRepository {
@Query(value = 'select * from users where username = :name', nativeQuery = true)
User findUserByName(@Param('name') String name);
}
This is t...
1
votes
2
answer
44
Views
Spring data jpa @Query - Cannot create an “AS” alias for a result map
I map the result of the following JPQL-Query directly to a SpecialCustomDto object instead of the used javax.persistency entity object MyEntity. But I do not know, how to access the COUNT(DISTINCT e.attributeB), which will be mapped to the SpecialCustomDto.
This is the query.
@Repository
public inte...
1
votes
2
answer
69
Views
How to filter null values in ArrayList
I have a very big code. I faced an issue where at very starting of code, null
gets inserted inside arraylist custlist i.e custlist looks like [null]. And after many lines of code, I had my code changes where I was building up Predicate using custlist as shown below:
CriteriaBuilder cb = entityManag...
1
votes
1
answer
4.3k
Views
Autowired filed is still null
I have the following class (which is a JPA entity listener):
@Service
public class AuditLogListener {
@Autowired
IDomainObjectDAO domainObjectDAO;
@PostLoad
public void saveOldData(DomainObject obj) {
domainObjectDAO.findAll();
System.out.println('after Load');
}
@PreUpdate
public void logChanges(Do...
0
votes
0
answer
3
Views
How can I (if I can) extend a composed repository?
I am trying to give a Generic Parrent repository to all my 'per aggregate root' repositories which I can later use polymorphically.
I have composed a parent 'composed repository'. Which is to be implemented by other specific Repositories.
@Repository
public interface ZoneNameJpaRepository extends Ge...
1
votes
2
answer
6.3k
Views
JPA CascadeType.ALL not deleting child records
Consider this use case.
class Category {
@OneToMany(cascade=CascadeType.ALL)
List applications = new ArrayList();
}
class Application {
@ManyToOne
Category category;
}
I understand that, On this case, when category will be deleted, application will also be deleted. But who takes care of join...