我正在构建一个同时使用hibernate和jdbc连接数据库的应用程序。 一开始,如果用户选择“1”,它将调用RicercatoreJDBC的“chiamaRicercaOfferta”方法,该方法调用数据库上的存储过程 它很棒! 主要的问题是当用户选择“2”因为应用程序应该在“RicercatoreHibernate”中使用hibernate连接调用相同的存储过程,但我读过这是不可能的,所以我只是想显示我的数据库但是我得到了这个投射错误,我不知道如何移动! 有谁可以帮助我吗?
错误讯息
线程“main”中的异常java.lang.ClassCastException:[Ljava.lang.Object;不能投它.Offerta
RicercatoreHibernate类
package it;
import org.hibernate.Session;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class RicercatoreHibernate implements Ricercatore{
public RicercatoreHibernate() {}
public boolean connetti() {
return false;
}
public void disconnetti() {}
public boolean isConnesso() {
return false;
}
//Operazione di Insert su Database
public int insertOfferta(int ID_offerta,String nomeAzienda, String titolo, int postiVacanti, String ID_randomOfferta ) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Offerta offerta = new Offerta(ID_offerta, nomeAzienda, titolo, postiVacanti, ID_randomOfferta);
//int ID_offerta = (Integer)session.save(offerta);
session.getTransaction().commit();
session.close();
return ID_offerta;
}
public ArrayList<Offerta> chiamaRicercaOfferta(String k)throws SQLException{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Offerta> lista =session.createSQLQuery("select o.ID_offerta, o.ID_randomOfferta, o.titolo, o.postiVacanti from OffertaLavoro o").list();
session.getTransaction().commit();
session.close();
return (ArrayList<Offerta>) lista;
}
public List<Offerta> list(){
Session session =HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Offerta> result = session.createSQLQuery("select o.ID_offerta, o.ID_randomOfferta, o.titolo, o.postiVacanti from OffertaLavoro o").list();
session.getTransaction().commit();
return result;
} }
主要类
package it;
import java.sql.*;
import java.util.*;
public class OffertissimApp {
public static void main(String[] args) throws SQLException {
String k=" ";
String risposta=" ";
Scanner in= new Scanner(System.in);
ArrayList<Offerta> lista =new ArrayList<Offerta>();
Welcome ciao = new Welcome();
RicercatoreFactory ricFactory =new RicercatoreFactory();
Ricercatore ilRicercatore = null;
System.out.println("Cosa vuoi fare?");
System.out.println("Digita 1 per effettuare una ricerca con JDBC");
System.out.println("Digita 2 per effettuare una ricerca con Hibernate");
Scanner userInput = new Scanner(System.in);
String tipoSelezionato = userInput.nextLine();
ilRicercatore = ricFactory.makeRicercatore(tipoSelezionato);
if(ilRicercatore == null) {
System.out.println("Devi selezionare una delle operazioni disponibili");
}
System.out.println("Vuoi effettuare una ricerca?");
System.out.println("Inserisci SI per continuare oppure NO per uscire");
risposta =in.next();
while (!(risposta.equals("no"))){
System.out.println("Inserisci una chiave di ricerca");
k=in.next();
lista =ilRicercatore.chiamaRicercaOfferta(k);
System.out.println("------------------Ecco i risultati!-----------------");
for (Offerta list:lista){
System.out.println(" ");
System.out.println(" ");
System.out.println("| ID_offerta | Nome Azienda | Titolo Offerta | numero posti vacanti | ID_randomOfferta |");
System.out.println(list);
System.out.println(" ");
}
System.out.println("Vuoi effettuare una nuova ricerca?");
System.out.println("Inserisci SI per continuare oppure NO per uscire");
risposta =in.next();
}
System.out.println("Ciao!");
in.close();
userInput.close();
}
}
Offerta POJO课程
package it;
import javax.persistence.*;
@javax.persistence.Entity(name = "OffertaLavoro")
//@Table(name = "OffertaLavoro")
public class Offerta {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int ID_offerta;
private String nomeAzienda;
@Column(name = "titolo", nullable = false)
private String titolo;
@Column(name = "postiVacanti", nullable = false)
private int postiVacanti;
@Column(name = "ID_randomOfferta", nullable = true)
private String ID_randomOfferta;
// private int fk_IDAzienda_offertaLAvoro;
// private Azienda azienda;
/*Costruttori*/
public Offerta() {
}
public Offerta(int ID_offerta, String nomeAzienda, String titolo,
int postiVacanti, String ID_randomOfferta) {
this.ID_offerta=ID_offerta;
this.nomeAzienda=nomeAzienda;
this.titolo=titolo;
this.postiVacanti=postiVacanti;
this.ID_randomOfferta=ID_randomOfferta;
}
public Offerta(int ID_offerta, String titolo,
int postiVacanti, String ID_randomOfferta) {
this.ID_offerta=ID_offerta;
this.titolo=titolo;
this.postiVacanti=postiVacanti;
this.ID_randomOfferta=ID_randomOfferta;
}
/**
* Metodi get
*
*/
@Id
public int getID_offerta() {
return this.ID_offerta;
}
public String getNomeAzienda() {
return this.nomeAzienda;
}
public String getTitolo() {
return this.titolo;
}
public int getPostiVacanti() {
return this.postiVacanti;
}
public String getID_randomOfferta() {
return this.ID_randomOfferta;
}
/*
public int getFk_IDAzienda_offertaLAvoro() {
return this.fk_IDAzienda_offertaLAvoro;
}
*/
/**
* Metodi set
*
*/
public void setID_offerta(int ID_offerta) {
this.ID_offerta=ID_offerta;
}
public void setNomeAzienda(String Azienda) {
nomeAzienda=Azienda;
}
public void setPostiVacanti(int vacanti) {
postiVacanti=vacanti;
}
public void setTitolo(String titolo) {
this.titolo=titolo;
}
public void setID_randomOfferta(String ID_randomOfferta) {
this.ID_randomOfferta=ID_randomOfferta;
}
/* @ManyToOne
* @JoinColumn(name="ID_azienda")
* public void setFk_IDAzienda_offertaLAvoro(int fk_IDAzienda_offertaLAvoro) {
* this.fk_IDAzienda_offertaLAvoro= fk_IDAzienda_offertaLAvoro;
* }
* public Azienda getAzienda() {
* return azienda;
* }
*
* public void setAzienda(Azienda azienda) {
* this.azienda=azienda;
* }
*/
//Override di hashCode
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ID_offerta;
return result;
}
//Override di equals
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Offerta))
return false;
final Offerta offerta =(Offerta) obj;
if(!offerta.getTitolo().equals(getTitolo()))
return false;
return true;
}
//Override di toString
public String toString() {
return " "+ ID_offerta +" "+ nomeAzienda +" "
+titolo +" "+ postiVacanti +" "+ ID_randomOfferta;
}
}
Hibernate cfg文件,如果有用的话
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory >
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.username">pippo</property>
<property name="hibernate.connection.password">pippo</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost\\sqlserver:1433;user=pollo;password=pollo;databaseName=Cosissime</property>
<property name="hibernate.default_schema">dbo</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.default_entity_mode">pojo</property>
<mapping class="it.Offerta"/>
<mapping class="it.Azienda"/>
</session-factory>
</hibernate-configuration>
我可以启动的存储过程
ALTER proc [dbo].[trovaLavoro]
@temp varchar(50)
--,@out varchar(50) OUTPUT
as
begin
print 'Inserisci titolo annuncio';
select o.ID_offerta, o.ID_randomOfferta,a.nomeAzienda, o.titolo, o.postiVacanti
from OffertaLavoro o join Azienda a on o.fk_IDAzienda_offertaLavoro= a.ID_azienda
where titolo like '%'+@temp+'%' --or titolo like '%%'
END
如果有其他东西我可以提供yoi到达解决方案只是让我知道! 非常感谢每个人都会帮助我!!
编辑1
我解决了这个问题,但现在它给了我这个
错误:Sintassi不同于prossimitàdi'@ P0'。 线程“main”中的异常org.hibernate.exception.SQLGrammarException:无法提取ResultSet 在org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106) 在org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) 在org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79) 在org.hibernate.loader.Loader.getResultSet(Loader.java:2122) 在org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1905) 在org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1881) 在org.hibernate.loader.Loader.doQuery(Loader.java:925) 在org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342) 在org.hibernate.loader.Loader.doList(Loader.java:2622) 在org.hibernate.loader.Loader.doList(Loader.java:2605) 在org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2434) 在org.hibernate.loader.Loader.list(Loader.java:2429) 在org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336) 在org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1980) at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322) 在org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125) at it.RicercatoreHibernate.chiamaRicercaOfferta(RicercatoreHibernate.java:45) at it.OffertissimApp.main(OffertissimApp.java:50) 引起:com.microsoft.sqlserver.jdbc.SQLServerException:在prossimitàdi'@ P0'中的Sintassi non corretta。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258) 在com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1535) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:467) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement $ PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:409) 在com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7151) 在com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2478) 在com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:219) 在com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:199) 在com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:331) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70) ......还有15个
我已经明白这个问题与不支持sql server 2017的hibernate方言有关
有关如何解决的任何提示?
答案 0 :(得分:0)
当您使用Hibernate的本机sql查询时,必须使用addEntity(Class entityType)方法,以便Hibernate可以理解必须为查询结果映射哪个类。 它看起来像这样:
session.createSQLQuery("select o.ID_offerta, o.ID_randomOfferta, o.titolo, o.postiVacanti from OffertaLavoro o").addEntity(Offerta.class).list();
但是,我建议使用HQL或JPQL进行此类简单查询