update Enum value in hibernate - java

I wrote a hql query where i want to update an enum value in database,but i don't know how to update an enum value.This is my model
#Entity
public class ImageInfo implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "ACTIVE")
private Integer active;
#Column(name = "NOTIFICATION_NUM")
private Integer groupNum;
#Column(name = "PUBLISHED_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date publishedTime;
#Column(name = "POSTED_TIME")
private Timestamp postedTime;
#Enumerated(EnumType.STRING)
private PublishIndicator publishIndicator;
}
you can see there is an enum field named "publishIndicator" . I want to update this field in a hql query.This is my query
session.createQuery("update ImageInfo img set img.active = 1
and img.publishIndicator = :publish where img.active = 0 and
img.publishedTime <:publishedTime ").setParameter("publishedTime",
date).setParameter("publish", PublishIndicator.PUBLISH).executeUpdate();
but i am getting an error
"java.lang.IllegalArgumentException: node to traverse cannot be null!"
i know i am doing something wrong with updating enum valur.How can i solve it?

Use your (fully qualified) PublishIndicator enum.
Instead of PublishIndicator.PUBLISH value, so something like this: (assuming your PublishIndicator enum is in com.image package), Use it as com.image.PublishIndicator.PUBLISH

Related

Named query to find all entities based on list (instance variable) containing certain values

is it possible using named queries to find all entities based on list containing a certain value.
I have an entity called User
public class User implements Serializable {
private static final long serialVersionUID = -82485348776234092345L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
#Size(min = 5, max = 50)
#Column(name = "email")
private String email;
#NotNull
#Size(min = 5, max = 50)
#Column(name = "password")
private String password;
#Column(name = "creationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = CascadeType.ALL)
private List<Phone> phoneNumbers;
/* Getters and Setters */
}
I am going to simplify the Phone entity for keeping this post clean:
public class Phone implements Serializable {
private static final long serialVersionUID = -34672347534985L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
#Column(name = "number")
private String number;
#Column(name = "type")
#Enumerated(EnumType.STRING)
private EPhoneType phoneType;
#Column(name = "creationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#ManyToOne
private User user;
/* Getters and Setters */
}
Now I need to find all the users that have the phone number, lets say: 289647.... and Phone.type = 'MOBILE'
Phone type is an enum.
I am not sure how to acheive this using a named query. With regular native query I can get this done using a JOIN on the tables. Has anyone done something like this with a NamedQuery
First of all, you are probably confusing "named queries" with "JPQL" queries.
A JPA query can be either "native" and "JPQL" - the difference is the query language (SQL or OQL-like; the first is record-oriented, the second is object-oriented).
Both types of queries can be dynamic (built in runtime) or static (aka "named", defined as a static part of the persistence context, just like the entities). The latter can be optimized by creating and storing prepared queries to represent them.
Joining in OQL-like languages (HQL, JPQL) is done in a similar way as in SQL, but they don't represent joining relations (tables) but rather - "object attributes". When joining on an attribute, you don't define any criteria, because these are already part of the entity's definition. On the other hand, joining will create a row per association between entities, so you probably want to use distinct clause (to avoid having User repeated as many times, as a matching Phone appears on the phoneNumbers list).
Probably what you want is:
select u from User u left join u.phoneNumbers n where n.type = :type and n.number = :number
The query above can be used both as named or unnamed variety, to run it you have to provide named parameters type and number: an enum and a string.

spring jpa custom query to return page<E>

I'm trying to get pagination from the list that I have using jpa repository. List is actually attribute of another object. It is, sort of, kind off, message board... Long story short, Class Tiket has a list of Poruka that I want to retrieve and paginate them. Here is what it looks like:
#Entity
#Table(name = "tiket")
public class Tiket implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="id")
private Long id;
#Column(name="naslov")
#NotEmpty(message= "Morate unijeti naslov tiketa")
private String naslov;
#Column(name = "tiket_datum")
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#NotNull
private Date tiketDatum;
#Column(name = "rijesen_datum")
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date rijesenDatum;
#ManyToOne(cascade = {CascadeType.REFRESH}, fetch=FetchType.EAGER )
#JoinColumn(nullable=false)
#NotNull
private Korisnik korisnik;
#OneToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER )
#GenericGenerator(name="uuid-gen", strategy = "increment")
#CollectionId(columns = #Column(name = "collection_id"), generator = "uuid-gen", type = #Type(type = "long"))
private List<Poruka> poruke = new ArrayList<Poruka>();
OK. List of Poruka is what I need.
So I tried creating custom query in PorukaRepository that would get the list of Poruka paginated by doing it like this:
public interface PorukaRepository extends JpaRepository<Poruka, Long> {
#Query("select t.poruke from Tiket t where t.id=?1")
Page<Poruka> findAllPoruke(Long tid, Pageable pageable);
}
and receive following error:
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 ') as col_0_0_ from tiket2 tiket2x0_, tiket2_poruka poruke1_, poruka poruka2_ whe' at line 1
then tried changing query, as the database has tiket_poruka table, to this:
#Query(value="SELECT * FROM poruka p where p.id IN (SELECT tp.poruke_id FROM tiket_poruka tp WHERE tp.tiket_id=?0)", nativeQuery = true)
Each time I receive following error during compilation:
No property find found for type ba.fit.vms.pojo.Poruka
then tried to put it in the TiketRepository... No luck. Then I added order by and sorting to my query, still no luck.
error this time is that it cannot convert from Tiket to Poruka
Of course, I can just retrieve the list and paginate it in my controller, but I want to learn and see if this is possible, as it seems logical. Do I need to create custom repository? Or just my query is wrong?
And here is the Poruka.class:
#Entity
#Table(name = "poruka")
public class Poruka implements Serializable{ //, Comparable<Poruka>
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="id")
private Long id;
#Column(name="sadrzaj", length = 255)
#NotEmpty(message= "Sadrzaj ne moze biti prazan")
private String sadrzaj;
#Column(name = "datum")
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#NotNull
private Date datum;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="korisnik_id", nullable=true)
private Korisnik korisnik;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="prethodna_id", nullable=true)
private Poruka prethodni;
Of course, classes are shown without getters and setters...

How to generate ID for entity from the existing ORACLE sequence?

I have a Table (for a long time ago), call it TABLE_A, and I have an entity class for this Table:
#Entity
#Table(name = "TABLE_A")
public class TableA implements Serializable {
#Id
#Basic(optional = false)
#Column(name = "ID")
//what else should I write here, to get the value from the existing sequence (seq_table_a_id) from database?
private Long id;
#Basic(optional = false)
#Column(name = "VALID_TO_DT")
private String name;
getters/setters...
}
I had created a sequence for this table in ORACLE a long time ago, and I want to give values for the new item's ID from this sequence. How should I write this code in java entity with annotations? If you could write an example for my code, that would be helpful!
And should I write anything else maybe in the persistance.xml?
The name of the existing sequence is: seq_table_a_id
You should check the annotation #GeneratedValue and #SequenceGenerator
#Id
#GeneratedValue(generator="seqGen")
#SequenceGenerator(name="seqGen",sequenceName="seq_table_a_id", allocationSize=1)
private Long id;
Check this link

ORACLE: org.hibernate.ObjectNotFoundException: No row with the given identifier exists

I am using Hibernate(3.0) + Oracle DB (10g) for my application.
My domain object are like PluginConfig.java
#Entity
#Table(name = "plugin_config" , schema = "test")
#org.hibernate.annotations.Cache(usage =org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)
public class Config {
private static final long serialVersionUID = -1959019321092627830L;
/** This object's id */
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected long id;
#OneToOne
#JoinColumn(name = "plugin_id")
private Plugin plugin;
#Column(name = "config_name")
#NaturalId(mutable = true)
private String name;
#Column(name = "config_desc")
private String description;
another domain object Plugin.java
#Entity
#Table(name = "plugin", schema = "test")
#org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)
public class Plugin implements Serializable {
private static final long serialVersionUID = 5694761325202724778L;
/** This object's id */
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected long id;
#Column(name = "plugin_name")
#NaturalId
private String pluginName;
#OneToOne
#JoinColumn(name = "plugin_config_id")
private PluginConfig pluginConfig;
#Column(name = "plugin_desc")
private String description;
Whenever i try to load Plugin via my database service method(using #Transactional annotation and hence it loads all its children as well) i get the following error
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [PluginConfig#53]
There is actually no row in plugin_config table with id = 53.
And also no plugin table entry has plugin_config_id=53.
So from where is hibernate picking these values ?
I noticed one thing here, the value "53" is actually the row number from the plugin_config table which should have been reffered.
See the below image:
This is the plugin config that my query should be looking for. But it tries to search it with identifier #53(Row no:) instead of the #95(value of the primary key "id").
Where can i be going wrong with this ?
I don't know if this is teh best solution, but you can use #NotFound annotation with IGNORE command to let Hibernate discard exception adn set pluginConfig to null.
#OneToOne
#JoinColumn(name = "plugin_config_id")
#NotFound(action = NotFoundAction.IGNORE)
private PluginConfig pluginConfig;

Mapping enum to string in hibernate

I've got a Category Hibernate model:
#Entity
#Table(name = "category")
public class Category {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "type")
private String type;
which have a type string field. Also I've got a Java enum which represent a type of a category:
public enum CategoryType {
INCOME, OUTCOME;
}
which I would like to use instead of the string type. The SQL accepts two distinct values in the varchar parameter: either CategoryIncome or CategoryOutcome. I would like the Category model class to accept an enum variable - and map it somehow to the string whenever hibernate asks for it.
Is it possible?
Yes, is possible. It should be:
#Enumerated(EnumType.STRING)
#Column(name = "category_type")
private CategoryType categoryType;
The accepted answer is not sufficient for PostgreSQL. I attach the implementation that worked for me:
https://stackoverflow.com/a/64021041/5279996
I had to add
#Column(columnDefinition = "VARCHAR(30)")
to #dcernahoschi solutions to make it work.
#Column(columnDefinition = "VARCHAR(30)")
#Enumerated(EnumType.STRING)
#Column(name = "category_type")
private CategoryType categoryType
Without I got the Exception
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "

Categories