Hibernate and Criteria Api generates wrong Join condition
I got following tables. Lets ignore the fact that the relation is done wrong here. I cannot change that. Each company can have multiple employes and each employe belongs to only one company.
Table: Company
ID | EMPLOYE_ID |
---|---|
10 | 100 |
Table: Employe
ID | NAME |
---|---|
100 (Same as EMPLOYE_ID) | John |
Now i want to create a relation @OneToMany between Company -> Employe . My entities look as follow
class Company {
@Id
@Column(name = "id", unique = true, nullable = false)
private String id;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "EMPLOYE_ID", referencedColumnName = "ID")
private Set<Employe> employees;
}
No matter if i try to create a uniderectional, or biderection relationship by adding also @ManyToOne on my Employe class, when using Criteria api to select all Company entities and their Employes i always end up with a wrong generated SQL query at the point where it joines the tables. The above relation for example creates following:
FROM company company0
INNER JOIN employe employe0 ON company0.id = employe0.employe_id
I tried several approaches, but i end up almost with the same error. It tries either to access a column which does not exist on the table, or joins wrong columns (e.g. id = id). Or by the following exception
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.Employe column: id (should be mapped with insert="false" update="false")"}}
What is a simple approach to create a bidrectional relation with the above table structure?
See also questions close to this topic
-
recursion method not returning a string
I have to create a code that can find the longest palindrome contained inside sentences. (eg. Some people like cake but I prefer pie; the longest palindrome is i prefer pi). The problem is that upon running the code it doesn't return the palindrome. I'm not sure what the problem is but if anyone can figure it out I'd appreciate you letting me know. Thanks!
Code is below...
public class Recursion6 { static String recursion(String word, int currentLength, int x, String substring) { String reverse =new StringBuffer(word).reverse().toString(); if(word.length() == 1 ){ return substring; } if(word.charAt(0) != word.charAt(x)) { if(x == word.length() - 1) { recursion(word.substring(1), currentLength, 1, substring); } x++; recursion(word, currentLength, x, substring); } else { if(word.substring(0, x + 1).equalsIgnoreCase(reverse.substring(word.length() - (x+1), word.length()))) { if(word.substring(0, x).length() > currentLength) { currentLength = word.substring(0, x + 1).length(); substring = word.substring(0, x + 1); } recursion(word.substring(1), currentLength, 1, substring); } recursion(word.substring(1), currentLength, 1, substring); } return substring; } public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.println("Enter a Sentence:"); String word=sc.nextLine(); System.out.println("The Palendrome is "+recursion(word.replaceAll(" ", ""), 1, 1, null)); sc.close(); } }
-
Groovy v3.0.7 doesn't support static interface methods
I have created a simple example groovy script under groovy v3.0.7, and Java 11.0.5
interface IFace { static String sMethod () { return "hello" } } class Test implements IFace { } IFace i = new Test() println i.sMethod()
however the parrot parser won't except this. If you run this you gives the following error
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: ideaGroovyConsole.groovy: 2: The method 'java.lang.String sMethod()' from interface 'IFace' must not be static. Only fields may be static in an interface. @ line 2, column 5. static String sMethod () { ^ 1 error
Why doesn't the latest 3.0.7 build support static interface methods. Have I missed something ?
-
HTTP Post method not supported by this URL when deployed to jboss EAP 7.1
I've a REST API, that is deployed on JBoss EAP 7.1. When I hit the URL at
http://localhost:8080/MyApp/group
in postman, it gives "HTTP method POST is not supported by this URL" error with status code 405.
When I deploy this API on embedded tomcat server, it works perfectly fine. Here is my controller
@RestController public class RequestController { @Autowired private GroupService groupService; @PostMapping( "/group" ) public GroupInfo fetchGroupInfo( @RequestBody GroupInfo groupInfo ) { long groupId = groupInfo.getGroupId(); return groupService.getGroup( groupId ); } }
main class
@SpringBootApplication public class MyApp extends SpringBootServletInitializer { /** * @param args */ public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){ return builder.sources(MyApp.class); } }
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> <groupId>com.my.package</groupId> <artifactId>MyApp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>MyApp</name> <packaging>war</packaging> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <finalName>MyApp</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
The deployment shows no error messages. However, it does show below warning
WARN [org.jboss.weld.deployer] (MSC service thread 1-4) WFLYWELD0013: Deployment optumRx-0.0.1-SNAPSHOT.war contains CDI annotations but no bean archive was found (no beans.xml or class with bean defining annotations was present).
And the class files are missing in the deployment folder in jboss. Can you please tell, what am I missing?
-
Spring boot Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception. using getter, ManyToMany relation
I've got two classes Participant and TimeWindow. Multiple participants can register for multiple TimeWindow, hence the ManyToMany relation
@Entity @Table public class Participant { @Id @SequenceGenerator( name = "participant_sequence", sequenceName = "particant_sequence", allocationSize = 1 ) @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "participant_sequence" ) private Long id; private String name; private String number; private String details; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "ParticipantCreneaux") private Collection<TimeWindow> registeredTimeWindow; public Participant() { } public Participant(String nom, String num, String details) { this.name = nom; this.number = num; this.details = details; this.registeredTimeWindow = new ArrayList<>(); } public void addTimeWindow(TimeWindow c){ registeredTimeWindow.add(c); } public void removeTimeWindow(TimeWindow c){ registeredTimeWindow.remove(c); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public Collection<TimeWindow> getRegisteredTimeWindow() { return registeredTimeWindow; } }
And the TimeWindow class:
@Entity @Table public class TimeWindow { @Id @SequenceGenerator( name = "creneau_sequence", sequenceName = "creneau_sequence", allocationSize = 1 ) @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "creneau_sequence" ) private Long id; private LocalTime hourStart; private LocalTime hourEnd; public Collection<Participant> getListParticipants() { return listParticipants; } @ManyToMany(fetch = FetchType.LAZY,cascade=CascadeType.ALL,mappedBy = "registeredTimeWindow") private Collection<Participant> listParticipants; public TimeWindow(LocalTime hourStart, LocalTime hourEnd) { this.hourStart = hourStart; this.hourEnd = hourEnd; this.listParticipants = new ArrayList<>(); } public TimeWindow() { } public LocalTime getHourEnd() { return hourEnd; } public void setHourStart(LocalTime hourStart) { this.hourStart = hourStart; } public void setHourEnd(LocalTime hourEnd) { this.hourEnd = hourEnd; } public LocalTime getHourStart() { return hourStart; } public int getNbParticipants(){ return listParticipants.size(); } public void addParticipant(Participant participant){ this.listParticipants.add(participant); } public void removeParticipant(Participant participant){ this.listParticipants.remove(participant); } public void setId(Long id) { this.id = id; } public Long getId() { return id; } }
Right now I'm still learning Spring boot, I haven't found anything about it so far or anything that helped me.
The error is when I summon my participant's TimeWindow Collection that i've gotten through the DataBase in the Config class. In the debugger my Participant looks like this
id:123 name:"hisName" number:"321" details:"some details" registeredTimeWindow:{PersistentBag@10927}Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.
At first i thought it was normal because of the Lazy option, i had to invoke the array through the getter, however it is wrong and the getter give me the exact same object.
FetchType.EAGER works fine, however I can't afford to do it. I've tried to get some help from someone a bit more experienced than I am, but without success. It should be possible to work around that issue within the JPA Repositories, but it feels like such a waste not to be able to use the getter.
-
Hibernate exhausted result set
I have a table which name is AsyncFcmNotification , this table has partitioned on a timestamp column. when I want to execute this query.
do { try (HibernateSession session = SessionManager.openSession()) { //noinspection unchecked List<AsyncFcmNotification> asyncFcmNotifications = session.createQuery("from AsyncFcmNotification where sent = false") .setFirstResult(offset) .setMaxResults(count) .list(); updateUnsendNotif(asyncFcmNotifications, session); offset += 100; } logger.info(offset + " notif has updated"); } while (offset < asyncFcmNotificationsCount);
asyncFcmNotificationsCount value is 105220;
I get these exceptions
-
Spring custom sorting in Sort.of
Is there any way to use
Sort.of
with this kind of sorting?@Query("SELECT l FROM Livestream l WHERE l.status IN ('LIVE', 'FUTURE') ORDER BY CASE WHEN l.status = 'LIVE' THEN -1 ELSE 0 END ASC") fun findLiveAndFuture(pageable: Pageable): Page<Livestream>
-
Where to Learn Java development(web development) without spring or springboot
I started to learn java web development. So I started with Springboot. I was able to understand Springboot but not in depth, for which I started to learn some concepts of spring which definitely helped. But now I want go deeper. So my question is,
a) Where should I learn raw Java web development as people used to do without Spring, Springboot, Hibernate and all the other tools, because without understanding this I wont ever get comfortable with Springboot or Spring. What books, video lectures or websites I should follow.
b) Should I even do this.(Keeping in mind I actually want go in depth)
-
Remote database connection with spring boot
I have connected remote database by following below properties:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://<server-ip>:3306/db_name spring.datasource.username= spring.datasource.password= spring.datasource.testWhileIdle=true spring.datasource.validationQuery=SELECT 1 spring.jpa.database=MYSQL spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=validate spring.jpa.generate-ddl=true spring.jpa.show-sql=true
I didn't get any error of database while building application. All crud operations are successfully done without any error while testing the application in local. But data is not updating in remote database. I didn't catch the issue. Could you please help me to solve that issue.
Thanks in advance.
-
Can't delete a collection of Laravel eloquent
I am retrieving a collection from db and want to delete it. This is the code.
$signal_id = $request->del_signal_id; $signal_details = VwDistressSignals::where('signal_id', $signal_id)->delete(); return "Success"; }
And this is the error.
message: "SQLSTATE[HY000]: General error: 1395 Can not delete from join view 'dvp.vw_distresssignals' (SQL: delete from `vw_distresssignals` where `signal_id` = 2)"
I have also tried giving all the column names. This is the model...
<?php namespace App\Models; use Reliese\Database\Eloquent\Model as Eloquent; class VwDistressSignals extends Eloquent { protected $table = 'vw_distresssignals'; }
-
How to use Dapper with Change Tracking to save an altered list?
I am looking at Dapper as ORM for our next project, but something is not clear to me.
In this question there are answers on how to do
inserts
,updates
anddeletes
.
Since this question is already a bit older, maybe there are better ways now a days..But my biggest concern is how to do an
ApplyUpdates
on a list.Suppose you have a
List<Customer>
that is build like shown hereAnd suppose you show this list in a DataGridView.
Now, the user will- alter the data of a few rows,
- insert a few new rows,
- delete a few rows
And when he clicks on the save button, at that time you want to save all these changes in this
List<Customer>
to your database, using Dapper.How can I go about that ?
If I have to loop through the list and for each row call an
insert, update or delete
statement, then how can I determine what operation to use ? Thedeleted
rows will be gone from the list.
I also want to make sure that if one statement fails, all will be rollbacked.
And I need the primary key for all new rows returned and filled in the DataGridView.In other words, all that ADO DataAdapter/DataTable does for you.
What is the best way to do this using
Dapper
?EDIT
The best way I can think of now is to keep 3 list in memory and when the user alters some data, add a row in theupdate list
, same forinsert list
anddeleted list
so I can run through these 3 list on the button click.
But I am hoping there is a better alternative build inDapper
for this kind of situation. -
How to serve joined tables in Java backend?
I am using ORM in my Java/Quarkus backend and some data is organized in normalized form. For example, in some tables I have id-s, which are representing textual names from another table. In other cases I have many-to-many relationship implemented via intermeiate table.
The problems are:
I need to show different sets of joined columns in different endpoints
I need to search and sort by different columns, including columns in related tables, with paging, so I need to do this with
SQL
Obvious idea is to use readonly entities for views. But looks like this is not well supported in
ORM
world. What are other options? -
criteria query eclipse link subquery where comparation does not work (lessThanOrEqualTo,greaterThanOrEqualTo...)
I have this:
//subquery whit max Subquery<Date> subqueryMaxDateCourses = query.subquery(Date.class); Root<ExpedienteCurso> subrootMaxDateCourses = subqueryMaxDateCourses.from(Course.class); subqueryMaxDateCourses.select(builder.greatest(subrootMaxDateCourses.get("dateField"))); //this code works as I expect (select * from ... where :date = (select max(date) from ...)) predicates.add(builder.equal(subqueryMaxDateCourses,filter.getDate())); //this code does not work predicates.add(builder.lessThanOrEqualTo(subqueryMaxDateCourses,filter.getDate()));
the second line throws this error:
java.lang.ClassCastException: org.eclipse.persistence.internal.jpa.querydef.SubQueryImpl cannot be cast to org.eclipse.persistence.internal.jpa.querydef.ExpressionImpl javax.faces.FacesException: #{expedienteSubvencionList.buscar}: java.lang.ClassCastException: org.eclipse.persistence.internal.jpa.querydef.SubQueryImpl cannot be cast to org.eclipse.persistence.internal.jpa.querydef.ExpressionImpl
I am using spring boot wiht: org.eclipse.persistence.jpa 2.7.4
I do not understand why the sencond line does not work.
-
Date comparison with Criteria and MongoTemplate
I am trying to apply MatchOperation and Criteria in MongoTemplate to find records with date less than specified date. I can query mongo console with following query:
db.aggregate([{$match: {createdAt:{$lt:ISODate('2021-04-18T19:00:00.000+05:30')}}}, {$group:{"_id": {campaignId:"$campaignId", siteContext:"$siteContext"}, "total":{$sum:1}}}])
In java I'm using the following code:
GroupOperation groupOperation = group("userId").count().as("total"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); Criteria criteria = Criteria.where("createdAt") .lt(dateFormat.format(new Date())); MatchOperation matchOperation = match(criteria); Aggregation aggregation = newAggregation(matchOperation, groupOperation);
The results are empty. The query works without the match operation. Is there any way to use ISODate in java? My class is as follows:
public class User{ @Id private String userId; private String name; @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @CreatedDate private Date createdAt; }
-
How do I make a calculation dependent on a certain classification?
I am trying to make my calculation dependent on which classification I have given my various observations.
An example of my data could look like this:
Permno R&D Industry Input 1 202 3 2 414 4 3 458 5 4 333 3 5 294 3 6 378 5 7 459 3 8 69 2 9 364 1 10 332 2 11 112 4 12 279 1 13 417 3 14 454 5 15 362 5 16 271 2 17 252 2 18 486 5 19 92 5 20 99 3
In my input variable, I want to e.g. have the following calculations:
If Industry = 1 then R&D / 2 If Industry = 2 then R&D / 2 If Industry = 3 then R&D / 6 If Industry = 4 then R&D / 8 If Industry = 5 then R&D / 12
How do I incorporate a criteria into my calculation like this?
Thanks!