Error with connection() to Hibernate - java

I encountered some errors connecting to Hibernate. This gives an error:
public static void makeReport(String type, Map<String, Object> param) throws JRException, IOException{
JasperPrint jasperPrint = null;
**Connection con = HibernateUtil.getSessionFactory().openSession().connection();**error here
String outputFileName = "Hóa đơn ";
JRAbstractExporter exporter = null;
if(type == "7" || type == "8" || type == "9"){
if(type==REPORT_BY_MONTH){
jasperPrint = JasperFillManager.fillReport("data\\Thống kê theo tháng.jasper", param, con);
outputFileName += "thống kê theo tháng " + param.get("#Month") + "-" + param.get("#Year") + ".xlsx";;
}
You can find the code project here.

I think you are trying to generated a JSper report for that you might need JDBC conventional Connection Object.
Are you trying to get JDBC Connection object you use this below code.
public void doWorkOnConnection(Session session) {
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
//use the connection here...
}
});
}
if you are looing for a Connection object just to interact with DB in hibernate way.
Session session - HibernateUtil.getSessionFactory().openSession();//or getSession()
Session object here is kind of wrapper class for JDBC conncetion object. you can sue Session object as Connection convention object JDBC procedure.

Related

How to test Methods from a SongServlet with JUnit 5

my Task ist to test a HttpServlet written in Java, which connects to a database and has the following methods implemented:
doGet(), doPost(), doDelete(), doOptions()
To test the functionality independently from the database connection I've implemented an InMemoryDao which populates a H2 database with test data from a Json file and gets injected into my ServletTest class.
Here's an example of the doGet() Method:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
boolean all = req.getParameter("all") != null;
boolean specific = req.getParameter("songId") != null;
if (all == specific) {
resp.setStatus(400);
writePlaintext(resp, "Specify either 'all' or 'songId'.");
return;
}
if (all) doGetAll(req, resp);
if (specific) doGetSpecific(req, resp);
}
My InMemorySongDao class looks like this:
public class InMemorySongDao extends MysqlSongDao {
public InMemorySongDao() throws SQLException {
super(new ComboPooledDataSource());
UUID uuid = UUID.randomUUID();
// Connect to a unique in-memory database identified by a random uuid
this.dataSource.setJdbcUrl("jdbc:h2:mem:" + uuid);
try (PreparedStatement st = this.dataSource.getConnection().prepareStatement(
"CREATE TABLE songs (" +
"id int not null primary key auto_increment," +
"title varchar(100) not null," +
"artist varchar(100)," +
"label varchar(100)," +
"released int" +
")")) {
st.execute();
}
}
/**
* Creates a songs dao prefilled with the songs from the given resource.
*/
public InMemorySongDao(String resourceName) throws SQLException, IOException {
this();
final ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(getClass().getResource(resourceName));
// Read array node or use empty node
ArrayNode array = (rootNode.isArray()) ? (ArrayNode) rootNode : mapper.createArrayNode();
try (PreparedStatement st = this.dataSource.getConnection().prepareStatement("INSERT INTO songs (id, title, artist, label, released) values (?,?,?,?,?)")) {
// Iterate over the array and populate the database with the songs
Iterator<JsonNode> elements = array.elements();
while (elements.hasNext()) {
JsonNode node = elements.next();
if (!node.isObject()) continue;
st.setInt(1, node.get("id").asInt());
st.setString(2, node.get("title").asText());
st.setString(3, node.get("artist").asText());
st.setString(4, node.get("label").asText());
st.setInt(5, node.get("released").asInt());
st.addBatch();
}
st.executeBatch();
}
}
}
Would be very thankful if somebody could provide me any help with this. Unfortunately I couldn't find any proper examples by research...
Kind Regards,
Mic

ERROR java.lang.NoClassDefFoundError: com/mongodb/MongoClient

so i got a very strange error message. Im currently working on a java web project with maven and testing the project with Eclipse and Tomcat. So I imported all the neccessary dependencys (mongo java driver, mongodb driver, mongodb driver core, bson and javax.servlet api), or so i thought. But still i'm getting this error over and over again.
If I run the code as part of a main method it works just fine...so im in the dark what could have caused this problem.
this is my MongoDB connector,
public class Connector {
final String HOST = "localhost";
final int PORT = 27017;
final String DBNAME = "mitfahrapp";
public static Connector instance;
public MongoClient connection;
public MongoDatabase database;
public Connector(){
this.connection = new MongoClient(this.HOST, this.PORT);
this.database = connection.getDatabase(DBNAME);
}
public MongoClient getClient() {
return connection;
}
public static Connector createInstance() throws UnknownHostException {
if (Connector.instance == null) {
Connector.instance = new Connector();
}
return Connector.instance;
}
public MongoCollection<Document> getCollection(String name) {
return this.database.getCollection(name);
}
public void CloseMongo() {
connection.close();
}
}
and this is part of my LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connector c = Connector.createInstance();
MongoCollection<Document> collection = c.getCollection("users");
String username = request.getParameter("username");
String password = request.getParameter("password");
Bson filterUsername = Filters.eq("username", username);
Bson filterPwd = Filters.eq("password", password);
Bson bsonFilter = Filters.and(filterUsername, filterPwd);
FindIterable<Document> doc = collection.find(bsonFilter);
if (doc != null) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
Thanks for any answers in advance!
This means that the classes are not included in the jar, if you are using maven you should use the maven shade plugin to include those.

Cannot capture XML returned by SQL Server stored procedure using Java

I am trying to run a SQL Server 2014 stored procedure from Java (Spring) code and get some xml results.
When I run this in a SQL client e.g. RazorSQL I get a bunch of xmls (which is expected because the there are multiple stored procedures within it, that returns those xml).
Here is the Exec call from my SQL client:
EXEC [dbo].[sp_GetType]
#TRAN_ID = 42
#QUAL_ID = 0
GetType does a RETURN 0 at the end (so basically if all steps succeed, it returns 0)
This opens multiple tabs in my client with the xmls.
And one example stored procedure within GetType has these lines:
SELECT TOP 1 ModifiedBy = CASE WHEN #IS_ID = 1 FROM TABLE23.dbo.TRX
TrxId WITH (NOLOCK) WHERE #DD_ID = #TRAN_ID
FOR XML AUTO, ELEMENTS
My goal is to capture all the xmls returned by GetType into a List of objects.
Here is my dao:
private final JdbcTemplate jdbcTemplate;
#Autowired
public TransactionDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Transactional(readOnly = true)
public List<Object> getTransaction(Integer tranId, Integer qualId) {
Object dt = new Object();
List<Object> resultList = (List<Object>) jdbcTemplate.execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException {
String storedProc = "{call sp_GetType(?,?)}";
CallableStatement cs = con.prepareCall(storedProc);
cs.setInt(1, tranId);
cs.setInt(2, qualId);
return cs;
}
}, new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement > cs) throws SQLException,
DataAccessException {
List<Object> results = new ArrayList<Object>();
cs.execute();
if(cs.getMoreResults())
{
ResultSet rs = cs.getResultSet();
while(rs.next()) //rs has only one record
{
InputStream in = null;
Clob clob = rs.getClob(1);
in = clob.getAsciiStream();
}
rs.close();
}
return results;
}
});
return resultList;
}
I'm using the jtds 1.3.1 driver (I tried connecting using mssql-jdbc but no luck).
Any help is much appreciated.

HikariCP- How to use dataSource.logWriter

HikariCP Github page have the following code:
props.put("dataSource.logWriter", new PrintWriter(System.out));
But I'm getting NullPointerException beacuse LogWriter isn't supported,
DriverDataSource final HikariCP class:
#Override
public PrintWriter getLogWriter() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
#Override
public void setLogWriter(PrintWriter logWriter) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
Is this solution for updating HikariCP logging is irrelevant?
I didn't get any answer in group
EDIT
Hikari initialization code uses PoolBase which is initializing datasource with DriverDataSource (which doesn't support logWriter):
else if (jdbcUrl != null && ds == null) {
ds = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password);
I must send jdbcUrl in Oracle and I failed setDataSourceClassName in conjunction with setDriverClassName

How to get OracleConnection for storing JGeometry to Oracle DB

I am trying store JGeometry to Oracle database with the following code:
#PersistenceContext
private EntityManager entityManager;
...
Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {
#Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("UPDATE SAMPLE_AREA SET GEOMETRY=? WHERE ID = " + sampleAreaId + " AND SAMPLE_ID = " + sampleId);
System.out.println(connection); // prints: org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler#321ca777[valid=true]
System.out.println(connection.getClass().getName()); // prints: com.sun.proxy.$Proxy125
STRUCT obj = JGeometry.store(jGeometry, connection);
ps.setObject(1, obj);
ps.execute();
}
});
I am getting java.lang.ClassCastException: com.sun.proxy.$Proxy125 cannot be cast to oracle.jdbc.OracleConnection when calling JGeometry.store.
How can I get OracleConnection?
I am using "hibernate.dialect = org.hibernate.dialect.Oracle10gDialect"
I figured out the solution. Instead of using Connection as parameter to JGeometry.store one needs to use OracleConnection. That can be unwrapped from Connection. I think I tried this before, but most likely I had wrong import, correct is oracle.jdbc.OracleConnection.
import oracle.jdbc.OracleConnection;
...
OracleConnection oracleConnection = connection.unwrap( OracleConnection.class );
STRUCT obj = JGeometry.store(jGeometry, oracleConnection);

Categories