JPA(Hibernate) cannot select Enum Type - spring-boot

#Entity
#Getter #Setter
public class MusicInfo
{
#Column(nullable = false)
#Enumerated(EnumType.STRING)
private MusicDifficulty difficulty;
}
public enum MusicDifficulty
{
EASY, NOMAL
}
.
jpa-ql> SELECT mi.difficulty FROM MusicInfo as mi
[2022-08-10 17:14:20] 24 rows retrieved starting from 1 in 242 ms (execution: 208 ms, fetching: 34 ms)
When enum type is inquired, the result exists, but the column cannot be retrieved.
What should I do to select the enum type?

If you create enum like this
public enum Currency {
EUR,
USD
}
then problem another place

Related

No property 'id' found for type 'Department', eventhough i given #id annotation, and tried with mySql database and h2 database

#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Department {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long departmentId;
private String departmentName;
private String departmentAddress;
private String departmentCode;
}
the above code is my entity class Department
#Repository
public interface DepartmentRepository extends JpaRepository<Department,Long> {
Department findDepartmentById(Long departmentId);
// Department getDepartmentById(Long deptId);
}
my repositoy interface DepartmentRepository
I am getting the below error.
Few days back I did the same code , everything same , it worked but now it is throwing this error, Please help me in solving this error
com.wipro.DepartmentmicroService.repository.DepartmentRepository.findDepartmentById(java.lang.String)! No property 'id' found for type 'Department'
Or you can use Optional<Department> findById(Long id) from JpaRepository.
It accepts #Id property.
#Repository
public interface DepartmentRepository extends JpaRepository<Department,Long> {
Department findByDepartmentId(Long departmentId);
}
In repository the method name should be findByDepartmentId, because , in sql it implements like select * from Department where departmentId = "some number"

JPA: Data integrity violation instead of Upsert

I have this entity with these fields and this primary key:
#Getter
#Setter
#Entity
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "MY_TABLE", schema = "MY_SCHEME")
public class MyEntity{
#Id
#Column(name = "ID")
private String id;
#Column(name = "NAME")
private String name;
#Column(name = "DESCRIPTION")
private String description;
}
I'm experiencing some undesirable behavior.If I try to insert the exact same data, I was expecting a primary key violation because it already exists, but I'm finding that what it's doing is an upsert. I am extending my repository from JpaRepository and using the save method:
#Repository
public interface MyJpaRepository extends JpaRepository<MyEntity, String> {
}
In my service:
...
this.repository.save(myEntity);
...
The database is Oracle, and if I launch the insert manually in SQL developer, the data violation occurs.
That could be happening?
Based on source code of save:
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Entity must not be null.");
if (entityInformation.isNew(entity)) { //it checks if entity is new based on id. i.e. insert operation.
em.persist(entity);
return entityx
} else {
return em.merge(entity); // just merging i.e. in your case doing upsert.
}
}
So currently save method works as expected; but if you really want to avoid upsert behaviour you might want to try using existsById; something like below:
if(!repository.existsById(..)){
repository.save(..);
}

find by property name in JPA repository returns the value of first row alone

I am new to spring boot and was trying to implement an sales related application. There i implemented a custom findBy method using property name customer id . The following is the output i am getting
[{"customerId":101,"stockId":1},{"customerId":101,"stockId":1},{"customerId":101,"stockId":1},{"customerId":101,"stockId":1}]
which is actually the first row but the values in table is different.
CUSTOMER_ID STOCK_ID
101 1
101 2
101 3
101 4
102 1
103 2
103 3
104 4
Since it is a sample start up application i didnt specify any constraints. what i am doing wrong here.
Update:
this is my Repository
#Repository
public interface CustomerSalesRepo extends JpaRepository<CustomerSales,Integer> {
public List<CustomerSales> findAllByCustomerId(int custID);
}
this is my sales entity
#Entity
#Table(name = CustomerSales.TABLE_NAME)
public class CustomerSales {
public static final String TABLE_NAME= "CUSTOMER_SALES";
#Id
#Column(name="CUSTOMER_ID")
private int customerId;
#Column
private int stockId;
data.sql
DROP TABLE CUSTOMER_SALES IF EXISTS;
CREATE TABLE CUSTOMER_SALES (customer_Id INT, stock_Id INT);
INSERT INTO CUSTOMERSALES (customer_Id,stock_Id)VALUES (101,1),(101,2),(101,3),(101,4),(102,1),(103,2),(103,3),(104,4);
I am not sure how you were able to populate that data set into your DB table since there is a primary key on customerId only. That means that you cannot have more than 1 row with CUSTOMER_ID = 101.
You should define a composite PK class
public class CustomerSalesPk implements Serializable
{
private int customerId;
private int stockId;
public int getCustomerId()
{
return customerId;
}
public void setCustomerId(final int customerId)
{
this.customerId = customerId;
}
public int getStockId()
{
return stockId;
}
public void setStockId(final int stockId)
{
this.stockId = stockId;
}
}
Then use this PK class in your entity
#Entity
#Table(name = CustomerSales.TABLE_NAME)
#IdClass(CustomerSalesPk.class)
public class CustomerSales
{
public static final String TABLE_NAME = "CUSTOMER_SALES";
#Id
#Column(name = "CUSTOMER_ID")
private int customerId;
#Id
#Column(name = "STOCK_ID")
private int stockId;

JPAs deleteAll leaves one entry left in the table. How can I clearly delete all entries?

I wrote some tests and found some crazy behavior.
#Test
public void clearTableOperation() {
service.deleteAll();
long existingEntriesAfterClear = service.count();
assertTrue(existingEntriesAfterClear == ZERO, String.format("DB Table not
empty after clear all operation: %s", existingEntriesAfterClear));
}
existingEntriesAfterClear is equal 1 not 0. Over 500 entries are deleted but this one left.
system print of last entry shows a real entry with id=0 value 1...value n to me.
Is it due to id=0 ? I have no other ideas.
MyRepository extends JpaRepository<MyEntity, Integer>
My Service
#CacheEvict(value = CachingConfiguration.CACHE_RESOLVER_NAME, allEntries = true)
public void deleteAll() {
repository.deleteAll();
}
I use HSQLDB and my Entity Class looks like
#Entity
#Table(name = "Cars")
public class Cars extends AuditEntitySupport<String> {
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", length = 10)
private int id;
...some more colums, setter, getter, toString
For testing reasons I
deleted the entry with id 0 from my sql import files -> everything works
changed the id 0 to 806 of the entry that survive deleteAll() - > everything works
replaced deleteAll() to repository.deleteAllInBatch(); -> works
Unfortunately, I do not understand the context

Date format in saved and returned entity (Spring-Data)

When I save entity in my repository personRepository.save(person) this returned object has a date in the format like this: Wed Dec 21 13:38:00 CET 2016. How I can change it to format like: 2016-12-21 13:38:00.732? Where this conversion is done, how this can be changed? In my database date saves in this format: 2016-12-21 13:38:00.732.
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "update_date")
private java.util.Date updateDate;
public interface PersonRepository extends CrudRepository<Person, Long> {}
You should use "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime". First of all, you change your person entity
#Entity
public class Person {
#Column(name = "update_date")
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime updateDate;
}
Then, update datetime in somewhere like PersonalImpl
import org.joda.time.LocalDateTime;
Class PersonalImpl {
void updatePerson(...){
Person person = new Person();
//do update person data
person.setUpdateDate(LocalDateTime.now());
}
}
PostgreSQL 9.5 show db
2014-09-10 07:59:14.822

Resources