I have a CDI bean with Java object which I use to display profile data from Database:
Parent Bean
#Named("DCProfileTabGeneralController")
#ViewScoped
public class DCProfileTabGeneral implements Serializable
{
public DCObj dc;
public class DCObj
{
private int componentStatsId; // COMPONENTSTATSID NUMBER(38,0)
........
// Default Constructor
public DCObj(){};
public DCObj(int componentStatsId....)
{
this.componentStatsId = componentStatsId;
.......
}
public int getComponentStatsId()
{
return componentStatsId;
}
public void setComponentStatsId(int componentStatsId)
{
this.componentStatsId = componentStatsId;
}
....
}
// Getters ------------------------------------------------------------------------------------
public DCObj getdcData()
{
return dc;
}
#PostConstruct
public void initData() throws SQLException
{
initDBData();
}
// Generate data Object from Oracle
public void initDBData() throws SQLException
{
dc = new DCObj(result.getInt("COMPONENTSTATSID"),
.........
}
}
Validator
#Named("ValidatorDatacenterController")
#ViewScoped
public class ValidatorDatacenter implements Validator, Serializable
{
public ValidatorDatacenter()
{
}
#Inject
private DCProfileTabGeneral profileTabGeneral;
// Validate Datacenter Name
public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
{
int componentStatsId = -1;
if (profileTabGeneral != null)
{
DCObj dcData = profileTabGeneral.dc;
if (dcData != null)
{
componentStatsId = dcData.getComponentStatsId();
}
}
if (componentStatsId == -1)
{
return;
}
String l;
String s;
if (value != null && !(s = value.toString().trim()).isEmpty())
{
if (s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
int resComponentStatsId = -1;
try
{
conn = ds.getConnection();
// if componentsstatsid <> edited componentstatsid in jsf -> throw validator exception
ps = conn.prepareStatement("SELECT componentstatsid from COMPONENTSTATS where NAME = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while (rs.next())
{
resComponentStatsId = rs.getInt(1);
}
if (resComponentStatsId != -1 && resComponentStatsId != componentStatsId)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' is already in use!", null));
}
}
catch (SQLException x)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" SQL error!", null));
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
}
else
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" This field cannot be empty!", null));
}
}
}
I have a custom validator which checks the input values from the profile page into the Database. I tested to get the Java object from the parent page using #Inject and to pass the Ojject to the validator. It turns out that I get empty Java object every time when I use #Inject.
I also tested to get Int using CDI. It works but when I again tested to get the Java Object again I get empty Object.
Can you tell me what is the proper way to call a Java Object from CDI bean? Why I cannot get Java object from CDI bean?
If I recall correctly CDI injection will not work with a validator. Use advanced from Myfaces CODI as the JSF-module from deltaspike is not ready yet. https://cwiki.apache.org/EXTCDI/jsf-usage.html
Or go for deltaspike and use the BeanProvider to get your instance.
BeanProvider.getContextualReference(DCProfileTabGeneral .class, false);
Related
I'am creating a restapi , i am using java spring and i'am getting the following error.
Error:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
My daoImpl class
#Override
public String getLoginDetails(VendorLogin vendorlogin) {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ?
and password=?";
String name =null;
try{
name = (String) jdbcTemplate.queryForObject(getVendorData,new Object[]{
vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()}, String.class);
}catch(Exception e){
e.printStackTrace();
}
return name;
}
my controller
#RequestMapping(value = Constants.REQ_MAP_LOGIN,
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public String vendorloginMethodPost(#RequestBody VendorLogin vendoridlogin) {
String message = Constants.EMPTY_STRING;
String id = dao.getLoginDetails(vendoridlogin);
String password = dao.getLoginDetails(vendoridlogin);
if (id == null && password==null) {
message = "login FAIL";
}else{
message =" login Successfully";
}
return message;
}
SOLUTION
#Override
public String getLoginDetails(VendorLogin vendorlogin) {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ? and password=?";
try {
name = (String) jdbcTemplate.queryForObject(
getVendorData,
new Object[]{vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()},
new RowMapper<YourVendorObject>() {
public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException {
// we suppose that your vendor_ID is String in DB
String vendor_ID = rs.getString("vendor_ID");
// if you wanna return the whole object use setters and getters
// from rs.getInt ... rs.getString ...
return vendor_ID;
}
});
return name;
} catch (EmptyResultDataAccessException e) {
return null;
}
}
public class EmptyResultDataAccessException extends IncorrectResultSizeDataAccessException
Data access exception thrown when a result was expected to have at least one row (or element) but zero rows (or elements) were actually returned.
The problem is, Spring throws an EmptyResultDataAccessException, instead of returning a null when record not found :
JdbcTemplate .java
package org.springframework.jdbc.core;
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
//...
public <T> T queryForObject(String sql, Object[] args,
RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return DataAccessUtils.requiredSingleResult(results);
}
DataAccessUtils.java
package org.springframework.dao.support;
public abstract class DataAccessUtils {
//...
public static <T> T requiredSingleResult(Collection<T> results)
throws IncorrectResultSizeDataAccessException {
int size = (results != null ? results.size() : 0);
if (size == 0) {
throw new EmptyResultDataAccessException(1);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, size);
}
return results.iterator().next();
}
check it here : source
try {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ? and password=?";
String name =null;
name = (String) jdbcTemplate.queryForObject(getVendorData,new Object[]{vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()}, String.class);
} catch (EmptyResultDataAccessException e) {
return null;
}
I m using ignite cache, I want to cache a view where the id is not relevant so implementing loadCache seems to be somehow tricky to me when there is no id!!!
How should I update the example below
public class CacheJdbcPersonStore extends CacheStoreAdapter<Long, Person> {
...
// This method is called whenever "IgniteCache.loadCache()" or
// "IgniteCache.localLoadCache()" methods are called.
#Override public void loadCache(IgniteBiInClosure<Long, Person> clo, Object... args) {
if (args == null || args.length == 0 || args[0] == null)
throw new CacheLoaderException("Expected entry count parameter is not provided.");
final int entryCnt = (Integer)args[0];
Connection conn = null;
try (Connection conn = connection()) {
try (PreparedStatement st = conn.prepareStatement("select * from PERSONS")) {
try (ResultSet rs = st.executeQuery()) {
int cnt = 0;
while (cnt < entryCnt && rs.next()) {
Person person = new Person(rs.getLong(1), rs.getString(2), rs.getString(3));
clo.apply(person.getId(), person);
cnt++;
}
}
}
}
catch (SQLException e) {
throw new CacheLoaderException("Failed to load values from cache store.", e);
}
}
...
}
clo.apply(person.getId(), person); this part is the issue in my logic my view doesn't have an ID
You need some unique ID to store data in Ignite. If there is nothing suitable in the actual data, your options are:
UUID.randomUUID()
Simple counter (id++) or LongAdder/AtomicLong - works only if you are loading from a single node
IgniteAtomicSequence - works across entire cluster
I have a spring boot tomcat-jdbc configuration with:
DataSource ds = new DataSource();
ds.setDriverClassName("oracle.jdbc.OracleDriver");
ds.setUrl("jdbc:oracle:thin:#10.101.7.16:1521:SIAMA");
ds.setUsername("xxx");
ds.setPassword("ccc");
ds.setInitialSize(10);
ds.setMaxActive(15);
ds.setMaxIdle(10);
ds.setMinIdle(5);
When i start tomcat i see in my database session 10 initial inactive session.
The problem is when the users starts app always user the same connection in database. The other 9 never use.
This is my code:
package com.csi_ti.itaca.custom.general.server.service;
import org.apache.tomcat.jdbc.pool.DataSource;
public class GeneralBusinessServiceImpl implements GeneralBusinessService {
public Connection conn;
ConversionUtil convert = new ConversionUtil();
#Autowired
#Qualifier("plsqlDataSource")
private DataSource plsqlDataSource;
#PostConstruct
public void init() throws SQLException {
System.out.println(">>>>> GeneralBusinessService Con 1");
conn = plsqlDataSource.getConnection();
}
public Connection obtenerConexion() {
System.out.println("Obtener conexion......................");
try {
if ( conn.isClosed()) {
System.out.println(">>>>>>>>>>> Conexión cerrada");
return conn = plsqlDataSource.getConnection();
}
else {
System.out.println(">>>>>>>>>>> Conexión ABIERTA");
conn.close();
conn = null;
System.out.println(">>>>>>>>>>> La cerramos");
conn = plsqlDataSource.getConnection();
System.out.println(">>>>>>>>>>> La volvemos a abrir " + conn.toString());
return conn;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void ejecutarConsulta() {
//System.out.println("Entramos a ejecutar consulta <<<<<<<<<<<<<<<<<<<*<*<*<*<*<*<*<*<*<*>*>*<*<" );
//System.out.println("Antes de Pob ****: " + conn);
System.out.println(">>>>> GeneralBusinessService Con 2");
PAC_SHWEB_PROVEEDORES llamada = new PAC_SHWEB_PROVEEDORES(conn);
try {
llamada.ejecutaPAC_SHWEB_PROVEEDORES__F_LISTA_TELEFONOS_EXPEDIENTE(new BigDecimal("906000060"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Pob ****: " + llamada.toString());
}
private Generico0DTO getDTO(Object obj){
System.out.println(">>>>> GeneralBusinessService Con 3");
Generico0DTO dto = new Generico0DTO();
List<Generico0.MapObject> listMapObjects= new ArrayList<Generico0.MapObject>();
if (obj!=null){
if (obj instanceof List<?>){
for (Map m :(List<Map>)obj){
Generico0.MapObject mapObject = new Generico0.MapObject();
mapObject.setMap(m);
listMapObjects.add(mapObject);
}
}else if (obj instanceof Map){
Generico0.MapObject mapObject = new Generico0.MapObject();
mapObject.setMap((Map)obj);
listMapObjects.add(mapObject);
}else if (obj instanceof BigDecimal){
Generico0.MapObject mapObject = new Generico0.MapObject();
Map map = new HashMap<String,BigDecimal>();
map.put("RETURN",obj);
mapObject.setMap(map);
listMapObjects.add(mapObject);
}
}
dto.setMapObject(listMapObjects);
return dto;
}
#Override
public Generico0 ejecutaPAC(String pac, String function, boolean tratarMensajes, Object... parameters) {
System.out.println(">>>>> GeneralBusinessService Con 4");
Map map;
try {
Class<?> clazz = Class.forName("com.csi_ti.itaca.custom.general.server.jdbc." + pac);
Constructor<?> constructor = clazz.getConstructor(Connection.class);
Object pacInstance = constructor.newInstance(conn);
String methodName = "ejecuta"+pac+"__"+function;
////System.out.println("LLamada pac: "+methodName);
Class<?>[] parameterTypes = new Class<?>[parameters.length];
Object[] parameterInput = new Object [parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].getClass().equals(Integer.class)) {
parameterTypes[i] = BigDecimal.class;
parameterInput[i] = new BigDecimal((Integer) parameters[i]);
} else {
parameterTypes[i] = parameters[i].getClass();
parameterInput[i] = parameters[i];
}
}
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
map = (Map) method.invoke(pacInstance, parameterInput);
if(tratarMensajes){
Object obj = Util.tratarRETURNyMENSAJES(map);
return getDTO(obj);
} else {
return getDTO(map);
}
} catch (Exception e) {
//System.out.println("Error_Service:"+e);
return null;
}
}
}
I need the pool to balance sessions for each request.
Any help ?
Thank you.
Your #PostConstruct method is bad and wrong. Instead of having the Connection conn variable that you initialize in your post construct, get a connection from the datasource whenever you need to use one.
try(Connection con = plsqlDataSource.getConnection()) {
// Do something with con
}
It's a lot simpler than what you've written too!
Your obtenerConexion() is unnecessary too. You are using a connection pool, you're not writing one.
You also shouldn't use org.apache.tomcat.jdbc.pool.DataSource directly, but rather javax.sql.DataSource.
I am new to Glassfish and Java EE, and I try to develop a project using glassfish as the server. The problem I have is that sometiems glassfish takes too long to deploy the project because it is closing JDBC Connections, and that takes too long.
SEVERE: Closing JDBC Connection 0
SEVERE: Closing JDBC Connection 1
SEVERE: Closing JDBC Connection 2
SEVERE: Closing JDBC Connection 3
SEVERE: Closing JDBC Connection 4
...........
SEVERE: Closing JDBC Connection 19
I don't know if the problem is from the glassfish server or from my code.. I am closing the connections after using them..
Can you please help me with figuring out where the problem comes from and how can I solve it?
I will add some more info.
I am using GlassFish Server 4.1 and Java EE 7 Web.
For connections, I have the following classes:
public class PooledConnection {
private Connection connection = null;
private boolean inuse = false;
// Constructor that takes the passed in JDBC Connection
// and stores it in the connection attribute.
public PooledConnection(Connection value) {
if (value != null) {
this.connection = value;
}
}
// Returns a reference to the JDBC Connection
public Connection getConnection() {
// get the JDBC Connection
return this.connection;
}
// Set the status of the PooledConnection.
public void setInUse(boolean value) {
inuse = value;
}
//Returns the current status of the PooledConnection.
public boolean inUse() {
return inuse;
}
// Close the real JDBC Connection
public void close() {
try {
connection.close();
} catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
}
}
The ConnectionPool class
public class ConnectionPool {
// JDBC Driver Name
private String driver = null;
// URL of database
private String url = null;
// Initial number of connections.
private int size = 0;
// Username
private String username = null;
// Password
private String password = null;
// Vector of JDBC Connections
private ArrayList<PooledConnection> pool = null;
private ArrayList<PooledConnection> poolInUse = null;
private ArrayList<PooledConnection> poolNotInUse = null;
public ConnectionPool() {
}
// Set the value of the JDBC Driver
public void setDriver(String value) {
if (value != null) {
driver = value;
}
}
// Get the value of the JDBC Driver
public String getDriver() {
return driver;
}
// Set the URL Pointing to the Datasource
public void setURL(String value) {
if (value != null) {
url = value;
}
}
// Get the URL Pointing to the Datasource
public String getURL() {
return url;
}
// Set the initial number of connections
public void setSize(int value) {
if (value > 1) {
size = value;
}
}
// Get the initial number of connections
public int getSize() {
return size;
}
// Set the username
public void setUsername(String value) {
if (value != null) {
username = value;
}
}
// Get the username
public String getUserName() {
return username;
}
// Set the password
public void setPassword(String value) {
if (value != null) {
password = value;
}
}
// Get the password
public String getPassword() {
return password;
}
// Creates and returns a connection
private Connection createConnection() throws Exception {
Connection con = null;
// Create a Connection
con = DriverManager.getConnection(url, username, password);
return con;
}
// Initialize the pool
public synchronized void initializePool() throws Exception {
// Check our initial values
if (driver == null) {
throw new Exception("No Driver Name Specified!");
}
if (url == null) {
throw new Exception("No URL Specified!");
}
if (size < 1) {
throw new Exception("Pool size is less than 1!");
}
// Create the Connections
try {
// Load the Driver class file
Class.forName(driver);
// Create Connections based on the size member
for (int x = 0; x < size; x++) {
System.err.println("Opening JDBC Connection " + x);
Connection con = createConnection();
if (con != null) {
// Create a PooledConnection to encapsulate the real JDBC Connection
PooledConnection pcon = new PooledConnection(con);
// Add the Connection to the pool
addConnection(pcon);
}
}
} catch (SQLException sqle) {
System.err.println(sqle.getMessage());
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// Adds the PooledConnection to the pool
private void addConnection(PooledConnection value) {
// If the pool is null, create a new vector with the initial size of
if(pool == null)
{
pool = new ArrayList<PooledConnection>(size);
}
pool.add(value);
}
public synchronized void releaseConnection(Connection con)
{
if(con != null)
{
// find the PooledConnection Object
for (int x = 0; x < pool.size(); x++) {
PooledConnection pcon = pool.get(x);
// Check for correct Connection
if (pcon.getConnection() == con) {
System.err.println("Releasing Connection " + x);
// Set its inuse attribute to false, which
// releases it for use
pcon.setInUse(false);
break;
}
}
}
}
// Find an available connection
public synchronized Connection getConnection() throws Exception {
PooledConnection pcon = null;
// find a connection not in use
for (int x = 0; x < pool.size(); x++) {
pcon = pool.get(x);
// Check to see if the Connection is in use
if (pcon.inUse() == false) {
// Mark it as in use
pcon.setInUse(true);
// return the JDBC Connection stored in the
// PooledConnection object
return pcon.getConnection();
}
}
// Could not find a free connection, create and add a new one
try {
// Create a new JDBC Connection
Connection con = createConnection();
// Create a new PooledConnection, passing it the JDBC Connection
pcon = new PooledConnection(con);
// Mark the connection as in use
pcon.setInUse(true);
// Add the new PooledConnection object to the pool
pool.add(pcon);
} catch (Exception e) {
System.err.println(e.getMessage());
}
// return the new Connection
return pcon.getConnection();
}
// When shutting down the pool, you need to first empty it.
public synchronized void emptyPool() {
// Iterate over the entire pool closing the JDBC Connections.
for (int x = 0; x < pool.size(); x++) {
System.err.println("Closing JDBC Connection " + x);
PooledConnection pcon = pool.get(x);
// If the PooledConnection is not in use, close it
if (pcon.inUse() == false) {
pcon.close();
} else {
// If it is still in use, sleep for 30 seconds and force close.
try {
java.lang.Thread.sleep(30000);
pcon.close();
} catch (InterruptedException ie) {
System.err.println(ie.getMessage());
}
}
}
}
}
And the DBAccessController
public final class DBAccessController {
private Connection connection = null;
public DBAccessController(String url, String userId, String password, boolean typereadonly) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
connection = DriverManager.getConnection(url, userId, password);
connection.setReadOnly(typereadonly);
} catch (java.lang.ClassNotFoundException exceptionClassNotFound) {
} catch (java.lang.InstantiationException instantException) {
} catch (java.lang.IllegalAccessException illegalAccess) {
} catch (java.sql.SQLException sqle) {
}
}
public DBAccessController(Connection con) {
if (con != null) {
this.connection = con;
}
}
public final synchronized ArrayList runSQL(String queryString, List<String> parametrii) {
try {
PreparedStatement prepStmt = connection.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(true);
for (int i = 0; i < parametrii.size(); i++) {
prepStmt.setString((i + 1), parametrii.get(i));
}
ResultSet rs = prepStmt.executeQuery();
boolean flag = prepStmt.execute();
ArrayList<HashMap<String, String>> rezultate = new ArrayList<>();
ResultSet keyset = prepStmt.getGeneratedKeys();
while (keyset != null && keyset.next()) {
HashMap<String, String> keysHM = new HashMap<>();
// Retrieve the auto generated key(s).
int key = keyset.getInt(1);
keysHM.put("cheia", Integer.toString(key));
rezultate.add(keysHM);
}
if (flag) {
ResultSet res = prepStmt.getResultSet();
ResultSetMetaData rsmd = res.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (res.next()) {
HashMap<String, String> hm = new HashMap<>();
Object o = res.getObject(i);
if (o != null) {
hm.put(rsmd.getColumnName(i), o.toString());
}
}
rezultate.add(hm);
}
res.close();
prepStmt.close();
return rezultate;
} else {
prepStmt.close();
if (keyset != null) {
return rezultate;
} else {
return null;
}
}
} catch (java.sql.SQLException sqle) {
return null;
}
}
public final synchronized ArrayList runSQL(String queryString) {
try {
PreparedStatement statement = connection.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(true);
boolean flag = statement.execute();
System.out.println("Statement: " + statement + " flag: " + flag);
ArrayList<HashMap<String, String>> rezultate = new ArrayList<>();
ResultSet keyset = statement.getGeneratedKeys();
while (keyset != null && keyset.next()) {
HashMap<String, String> keysHM = new HashMap<>();
// Retrieve the auto generated key(s).
int key = keyset.getInt(1);
keysHM.put("cheia", Integer.toString(key));
rezultate.add(keysHM);
System.out.println("Cheile " + keyset.toString());
}
System.out.println("Cheile " + keyset.toString());
if (flag) {
ResultSet res = statement.getResultSet();
ResultSetMetaData rsmd = res.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
System.out.println("res: " + res + " rsmd: " + rsmd + " numberOfColumns: " + numberOfColumns);
while (res.next()) {
HashMap<String, String> hm = new HashMap<>();
System.out.println("Res to string " + res.toString());
for (int i = 1; i <= numberOfColumns; i++) {
System.out.println("obiectul " + i + " res.getObject(i) " + res.getObject(i));
Object o = res.getObject(i);
System.out.println("rsmd.getColumnName(i) " + rsmd.getColumnName(i));
if (o != null) {
hm.put(rsmd.getColumnName(i), o.toString());
}
}
rezultate.add(hm);
}
res.close();
statement.close();
System.out.println("Return rezultate");
return rezultate;
} else {
System.out.println("Return null 1");
statement.close();
if (keyset != null) {
return rezultate;
} else {
return null;
}
}
} catch (java.sql.SQLException sqle) {
System.out.println("Return null 2" + sqle.getMessage());
return null;
}
}
public final void stop() {
try {
connection.close();
} catch (java.sql.SQLException e) {
}
}
}
When I need to use a connection I do the following (for example):
Connection con;
try {
con = cp.getConnection();
udao = new UtilizatorDAO(con);
con.close();
}
} catch (Exception ex) {
Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
}
out.close();
I try to map an object in my database.
It works fine for simple type like int, string ect... However i got a problem about a class containing an other object.
For example i got a class order :
public class order
{
int id;
Client c;
public int getId();
public void setId(int id);
}
and a class client :
public class Client
{
int id;
//some stuff like name ect and getter/setter...
}
I would like to map order by getting client id.
The problem is that when i try to get the package name of field Client it return me java.lang (package of field class...)
field.getType().getClass().getPackage().getName().compareTo("fr.javatp.model") == 0
I don't know why it doesn't return the type Client...
Any clue ?
this is code :
public void insertObject(Object instance) throws SQLException,
SecurityException, IllegalArgumentException,
InstantiationException, IllegalAccessException,
IntrospectionException, InvocationTargetException
{
Connection connection = null;
PreparedStatement preparedStatement = null;
this.type = instance.getClass();
this.query = createInsertQuery();
try
{
try
{
connection = this.getConnexion();
}
catch (Exception e)
{
e.printStackTrace();
}
preparedStatement = connection.prepareStatement(query);
int i = 0;
Class clazz;
for (Field field : type.getDeclaredFields())
{
System.out.println("PACKAGE NAME : " + field.getType().getClass().getPackage().getName());
if (field.getType().getClass().getPackage().getName().compareTo("fr.javatp.model") == 0)
clazz = field.getType();
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
field.getName(), type);
Method method = propertyDescriptor.getReadMethod();
Object value = method.invoke(instance);
preparedStatement.setObject(++i, value);
}
preparedStatement.addBatch();
preparedStatement.executeBatch();
}
finally
{
connection.close();
preparedStatement.close();
}
}
and create Insert query code :
private String createInsertQuery()
{
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(type.getSimpleName());
sb.append("(");
sb.append(this.getCol(false));
sb.append(")");
sb.append(" VALUES (");
sb.append(this.getCol(true));
sb.append(")");
System.out.println("QUERY TO SEND : " + sb.toString());
return sb.toString();
}
and get Col code :
private String getCol(boolean usePlaceHolders)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Field f : this.type.getDeclaredFields())
{
// System.out.println("PACKAGE NAME : " + f.getType().getClass().getName());
if (first)
first = false;
else
sb.append(",");
if (usePlaceHolders)
sb.append("?");
else if (f.getType().getClass().getPackage().getName().compareTo("fr") == 0)
{
sb.append(f.getName() + ".id");
}
else
sb.append(f.getName());
}
return sb.toString();
}
The problem is this expression:
field.getType().getClass().getPackage()
Field.getType() returns the Class object of the field you are interested in. By calling getClass() on it, you are getting the class object of Class, which is java.lang.Class.class. So instead just use
field.getType().getPackage()
Have you thought about using an existing ORM instead of reinventing the wheel?