Serverless framework with java MySQL conexion - java

I'm new with serverless framework. I'm trying to make a test of a simple application with maven, spring, hibernate, jpa, mysql and serverless.
this is my project
As a restApi works ok, but when I invoke the function in serverless terminal the information came null, because is not getting the info from the db.
this is my code
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="serverless-java" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.serverless.persistence.Wizard</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://mydb.uiyfuas7434.us-east-1.rds.amazonaws.com:3306/mydb" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="1234" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<!-- Important -->
<property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.max_size" value="10" />
<property name="hibernate.c3p0.min_size" value="0" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="120" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="240" />
<!-- Features -->
<property name="hibernate.connection.autoReconnect" value = "true"/>
<property name="hibernate.show_sql" value = "false" />
<property name="hibernate.connection.autoReconnectForPools" value = "true"/>
<property name="hibernate.connection.is-connection-validation-required" value = "true"/>
</properties>
</persistence-unit>
</persistence>
my Handler class
public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
private static final Logger logger = LoggerFactory.getLogger(TestService.class);
#Autowired
private IBaseService service;
#Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
List<Wizard> prueba = service.getWizards();
Map<String, Wizard> response = new HashMap<>();
Response responseBody = new Response("success", response);
try {
for (Wizard entity : prueba) {
response.put(entity.getName(), entity);
}
responseBody.setInput(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
responseBody.setMessage("Fail: " + e.getMessage());
}
return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody)
.setHeaders(Collections.singletonMap("This is a test", "AWS Lambda & serverless")).build();
}
}
my serverless.yml
service: aws-java-maven # NOTE: update this with your service name
provider:
name: aws
runtime: java8
iamRoleStatements:
- Effect: "Allow"
Action:
- "mysql:*"
Resource: "*"
package:
artifact: target/hello-dev.jar
functions:
get-transactions:
handler: com.serverless.Handler

Related

How to Initialize persistance.xml variables on program start?

Basically I am doing a Insert inside a PostgreSQL database, but since I have multiple databases I have to change the configurations based on each environment.
The thing is that I used a not really good way to do so, since everytime I do a insert, I replace all variables, which is ultra slow and definetly not a good way to achiev that.
How would I be able to do the same inserts, but having it configured while my Api started?
Here's what i'm currently doing:
package br.jus.tjba.dje.local.service;
import br.jus.tjba.dje.local.entity.Conteudo;
import br.jus.tjba.dje.local.repository.ConteudoRepository;
import br.jus.tjba.tjfw4.core.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
#Service
public class ConteudoService extends AbstractService {
#Autowired
private ConteudoRepository conteudoRepository;
public EntityTransaction insertInDb(String something, String somethingElse) {
Map<String, String> env = System.getenv();
Map<String, Object> configOverrides = new HashMap<>();
// Here I change my persistance.xml configs
for(Map.Entry<String, String> entry: env.entrySet()) {
if (entry.getKey().contains("DATABASE_URL")) {
configOverrides.put("javax.persistence.jdbc.url", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_USER")) {
configOverrides.put("javax.persistence.jdbc.user", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_PASSWORD")) {
configOverrides.put("javax.persistence.jdbc.password", env.get(entry.getValue()));
}
}
// Cria um factory dando override nas variáveis.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("default", configOverrides);
EntityManager conteudoManager = factory.createEntityManager();
Query query = conteudoManager.createNativeQuery("INSERT INTO something(" +
"SOMETHING," +
"SOMETHING_ELSE)" +
" VALUES (" +
":something," +
":somethingElse)");
conteudoManager.getTransaction().begin();
query.setParameter("something", something);
query.setParameter("somethingElse", somethingElse);
query.executeUpdate();
return conteudoManager.getTransaction();
}
public Conteudo getContent() {
return conteudoRepository.getContent();
}
}
Also my persistance.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="javax.persistence.jdbc.url" value="url" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.user" value="login" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>

How can I generate UTF8 table using hibernate

I am using hibernate version: 4.3.8.Final
In web.xml i have:
`
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.validator.apply_to_ddl" value="true" />
<property name="hibernate.connection.CharSet" value="utf8" />
<property name="hibernate.connection.characterEncoding" value="utf8" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="300"/>`
When I run app, hibernate generate all table in: latin1_swedish_ci
I read a lot of pages on google, but nothing help me.
How can I generate utf8 table using hibernate? IT IS POSSIBLE?
Thank you for any help.
If you check the org.hibernate.dialect.MySQL5InnoDBDialect implementation you'll find this :
package org.hibernate.dialect;
/**
* #author Gavin King, Scott Marlow
*/
public class MySQL5InnoDBDialect extends MySQL5Dialect {
public boolean supportsCascadeDelete() {
return true;
}
public String getTableTypeString() {
return " ENGINE=InnoDB";
}
public boolean hasSelfReferentialForeignKeyBug() {
return true;
}
}
So you can see in getTableTypeString the return value, what you can do is extends the MySQLDialect class and override getTableTypeString method to return
"ENGINE=InnoDB DEFAULT CHARSET=utf8";
Otherwise (you can try a lazy solution) try with adding UseUnicode=true&characterEncoding=utf8 at the end of your database connection url

WebSphere no persistent classes found for query class

I'm new to WebSphere and am trying to host a simple website that I can log into using an Oracle database.
I can get to my website, but when I try and log in I get the following warning and am not able to log in:
[WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null.
[WARNING ] HHH000183: no persistent classes found for query class: select a FROM com.model.User a where username = 'user'
No entity found for query
The warning no persistent classes found for query class: is being thrown when I try and create the query to log in inside of my CommonServiceImple.java:
Query query = getEntityManager().createQuery("select a FROM " + className + " a where username = '" + username + "'");
The No entity found for query is caused in the next line trying to run the query. This is because the query object is null because of the previous warning: Object obj = query.getSingleResult();.
server.xml
<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
<jdbcDriver id="oracle-driver" libraryRef="oracle-lib">
<library></library>
</jdbcDriver>
<connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
<properties.oracle URL="jdbc:oracle:thin:#crappie.ddvc.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
<fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>
web.xml
<resource-ref>
<description>DataSource</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
<mapped-name>jdbc/test</mapped-name>
</resource-ref>
ibm-web-bnd.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd
xmlns="http://websphere.ibm.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
version="1.0">
<virtual-host name="default_host" />
<resource-ref name="jdbc/test" binding-name="jdbc/test"/>
</web-bnd>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="pu1">
</persistence-unit>
</persistence>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="commonService" class="com.service.CommonServiceImpl"/>
<bean id="mainMenuService" class="com.service.MainMenuServiceImpl"/>
<bean id="storeFilterService" class="com.service.StoreFilterServiceImpl"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="ORACLE" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="pu1" />
<property name="jpaProperties">
<props>
<prop key="org.hibernate.envers.store_data_at_delete">true</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/test</value>
</property>
<property name="cache"
value="true"/>
<property name="lookupOnStartup"
value="true"/>
<property name="resourceRef"
value="true"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="pum"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="loginAction" scope="prototype" class="com.action.LoginAction">
<constructor-arg ref="commonService" />
</bean>
<bean id="userAction" scope="prototype" class="com.action.UserAction">
<constructor-arg ref="commonService" />
</bean>
</beans>
Nothing interesting in User.java
#Entity
#Table(name="WEB_PAGE_USERS")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="seq")
#SequenceGenerator(name="seq", sequenceName="WEB_PAGE_USERS_ID_SEQ")
private Integer id;
private String username;
private String password;
private String name;
//...
}
Or the ComonServiceImpl.java
#Transactional
public class CommonServiceImpl implements CommonService{
private EntityManager em;
#PersistenceContext(unitName="pu1")
public void setEntityManager(EntityManager em) {
this.em = em;
}
// MTD added for explicit order by
#SuppressWarnings("unchecked")
public List<Object> findAll(String name) {
getEntityManager().clear();
String sql = "select a FROM " + name + " a";
Query query = getEntityManager().createQuery(sql);
return query.getResultList();
}
//...(other sql selects, updates, inserts)
}
LoginAction.java
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private CommonService service;
private String username;
private String password;
private String environment;
public LoginAction(CommonService service) {
this.service = service;
}
public String execute() throws Exception {
return Action.SUCCESS;
}
#SuppressWarnings({ "unchecked", "static-access" })
public String login() throws Exception {
//Encrypt input password
CEncrypt cEncrypt = new CEncrypt();
String encryptedPwd = cEncrypt.encryptString(password);
//Get user by Username
User user = (User) service.findUser(username, User.class.getName());
//Check if input password is the same as the password in the database & login
if (user!=null && user.getPassword().equals(encryptedPwd)) {
#SuppressWarnings("rawtypes")
Map session = ActionContext.getContext().getSession();
session.put("logged-in","true");
session.put("loggedIn", "true");
session.put("WebAdminUserID", user.getUsername());
session.put("WebAdminUsername", user.getName());
session.put("WebAdminID", user.getRole_id());
return Action.SUCCESS;
} else {
return Action.ERROR;
}
}
//...
}
UPDATE
I was able to test my connection to the datasource by manually calling the lookup. But since my website is built on the persistence unit I would like to fix that error instead of re-writing the project to call the connection directly like this:
public String getEnvironment() {
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource test = (DataSource)envCtx.lookup("jdbc/test");
Connection con = test.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from WEB_PAGE_USERS where username = 'user'");
while(rs.next()){
System.out.println("username="+rs.getString("username")+", password="+rs.getString("password")+", role id="+rs.getString("role_id"));
}
// environment = "[" + (String)envCtx.lookup("Environment") + "]";
} catch (Exception e)
{
System.out.println("Environment Exception: " + e.getMessage());
}
return environment;
}
Which does return the correct data username=user, password=password, role id=1
To fix my answer I had to add every model class I had with the #Entity annotation to my persistence.xml file. It seems that even though I am using an entityManager I still needed to specify all of the #Entity classes (normally in Tomcat the entityManager would automatically find all of the classes).
Also I was getting that [WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null. warning which was causing my session to be cleared each time a page loaded (makes it hard to stay logged in). So I increased the length to 28 in the server.xml on WebSphere.
server.xml
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>jsp-2.2</feature>
<feature>jndi-1.0</feature>
<feature>jdbc-4.0</feature>
<feature>localConnector-1.0</feature>
<feature>servlet-3.0</feature>
<feature>jaxrs-1.1</feature>
</featureManager>
<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint host="localhost" httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>
<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
<jdbcDriver id="oracle-driver" libraryRef="oracle-lib"/>
<connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
<properties.oracle URL="jdbc:oracle:thin:#crappie.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
<fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>
<applicationMonitor updateTrigger="mbean"/>
<webApplication id="WebAdmin" location="WebAdmin.war" name="WebAdmin"/>
<httpSession idLength="28"></httpSession>
</server>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="pu1">
<class>com.model.App</class>
<class>com.model.AudioType</class>
<class>com.model.AuditRevisionEntity</class>
<class>com.model.ClosedGroup</class>
<class>com.model.ClosedSchedule</class>
<class>com.model.ClosedScheduleGroup</class>
<class>com.model.Department</class>
<class>com.model.Dnis</class>
<class>com.model.DnisVoiceTalent</class>
<class>com.model.GlobalXferGroupTemplate</class>
<class>com.model.Language</class>
<class>com.model.Location</class>
<class>com.model.MainMenu</class>
<class>com.model.NameValue</class>
<class>com.model.NameValueFunction</class>
<class>com.model.NameValueType</class>
<class>com.model.Peg</class>
<class>com.model.PegType</class>
<class>com.model.PharmacyConfig</class>
<class>com.model.Promo</class>
<class>com.model.PromoMessage</class>
<class>com.model.PromoSchedule</class>
<class>com.model.PromoType</class>
<class>com.model.Role</class>
<class>com.model.Schedule</class>
<class>com.model.ScheduleHours</class>
<class>com.model.ScheduleRecording</class>
<class>com.model.ScheduleType</class>
<class>com.model.Server</class>
<class>com.model.SpecialSchedule</class>
<class>com.model.SpecialScheduleRecording</class>
<class>com.model.Store</class>
<class>com.model.StoreAudio</class>
<class>com.model.StoreClosedGroup</class>
<class>com.model.StoreDepartment</class>
<class>com.model.StorePromo</class>
<class>com.model.StoreSchedule</class>
<class>com.model.StoreSpcSchedule</class>
<class>com.model.StoreType</class>
<class>com.model.StoreXferGroup</class>
<class>com.model.SystemMaintenance</class>
<class>com.model.TargetSystem</class>
<class>com.model.Timezone</class>
<class>com.model.Title</class>
<class>com.model.User</class>
<class>com.model.UserWebPage</class>
<class>com.model.UserWebPageAccess</class>
<class>com.model.UserWebPageClassType</class>
<class>com.model.VoiceTalent</class>
</persistence-unit>
</persistence>

Spring PropertyPlaceholderConfigurer load from DB

Is it possible to load properties from DB with Custom Spring PropertyPlaceholderConfigurer?
and is it also possible that datasource provided to custom PropertyPlaceholderConfigurer use specific property file in classpath?
I could not find satisfied answer from following links?
http://www.mkyong.com/spring/spring-propertyplaceholderconfigurer-example/
http://www.codeproject.com/Articles/28893/Loading-Application-Properties-from-a-Database
PropertyPlaceholderConfigurer to look for DB values and use properties file as fallback
Spring Context XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="false"/>
<property name="order" value="1" />
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<bean id="dataSourceimos" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass"><value>${imosdb.driver}</value></property>
<property name="jdbcUrl"><value>${imosdb.url}</value></property>
<property name="user"><value>${imosdb.username}</value></property>
<property name="password"><value>${imosdb.password}</value></property>
<property name="initialPoolSize"><value>${imosdb.initial_pool_size}</value></property>
<property name="maxPoolSize"><value>${imosdb.max_pool_size}</value></property>
<property name="minPoolSize"><value>${imosdb.min_pool_size}</value></property>
<property name="acquireIncrement" value="1"/>
<property name="acquireRetryAttempts" value="1"/>
<property name="idleConnectionTestPeriod" value="30"/>
<property name="preferredTestQuery" value="select 1 from dual"/>
<property name="checkoutTimeout" value="5000"/>
<property name="maxAdministrativeTaskTime" value="120"/>
<property name="numHelperThreads" value="10"/>
</bean>
<bean
class="com.ahmetk.property.DbPropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="order" value="2" />
<property name="placeholderPrefix" value="${" />
<property name="placeholderSuffix" value="}" />
<property name="dataSourceName" value="dataSourceimos" />
<property name="locations">
<list>
<value>classpath:static.properties</value>
<value>file:static.properties</value>
</list>
</property>
</bean>
<context:component-scan base-package="com.mkyong.rest" />
<bean id="transactionBo" class="com.mkyong.transaction.impl.TransactionBoImpl" />
<bean id="cacheServiceInterface" class="com.ttech.tims.imos.data.cache.CacheServiceImpl" />
<bean id="iCacheService" class="com.ttech.tims.imos.data.cache.impl.CacheService" />
</beans>
Java PlaceholderClass
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class DbPropertySourcesPlaceholderConfigurer extends PropertyPlaceholderConfigurer
{
private static final String DEFAULT_DATASOURCENAME = "dataSource";
private static final String DEFAULT_DBTABLENAME = "property";
private static final String DEFAULT_DBKEYCOLUMNNAME = "key";
private static final String DEFAULT_DBVALUECOLUMNNAME = "value";
String dataSourceName;
String dbTableName;
String dbKeyColumnName;
String dbValueColumnName;
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
DataSource dataSource = (DataSource) beanFactory.getBean(getDataSourceName());
// DbProperties dbProps = new DbProperties(dataSource);
final Properties dbProps = new Properties();
dbProps.put("app.version", "v3");
setProperties(dbProps);
super.postProcessBeanFactory(beanFactory);
}
public String getDataSourceName() {
return dataSourceName==null?DEFAULT_DATASOURCENAME:dataSourceName;
}
public void setDataSourceName(String dataSourceName) {
this.dataSourceName = dataSourceName;
}
}
Special thanks to writer of following pages.
http://ykchee.blogspot.com.tr/2012/09/spring-31-loading-properties-for-xml.html
http://blog.javaforge.net/post/31720600427/configuring-spring-based-web-application-from-database
http://www.javacodegeeks.com/2012/11/spring-3-1-loading-properties-for-xml-configuration-from-database.html

Null Pointer Exception EntityManager spring

i'm getting a null pointer exception when i'm trying to persist.
i'm going to list files that i think related with the error .
can someone help me ?
this is my class opmanagerImpl
package com.ensi.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ensi.entitis.opération;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public class opmanagerImpl implements opmanager {
#PersistenceContext(unitName="ERP_PCD")
private EntityManager em;
public opmanagerImpl(){};
public void creerOpération(opération op) {
if(em==null)System.out.print("error ");
em.persist(op);
}
}
this is my persistence.xml
<persistence-unit name="ERP_PCD" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/persistance" />
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="ensien" />
</properties>
</persistence-unit>
this is my applicationContext.xml
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.postgresql.jdbc.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5432/persistance"></property>
<property name="username" value="postgres"></property>
<property name="password" value="ensien"></property>
</bean>
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="datasource"></property>
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ERP_PCD"></property>
</bean>
<bean id="em" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean name="dao" class="com.ensi.dao.opmanagerImpl"> </bean>
<bean name="metier" class="org.ensi.metier.TestImpl">
<property name="op" ref="dao"></property>
</bean>
<context:annotation-config></context:annotation-config>
the main:
package com.ensi.dao;
import org.ensi.entitis.opération;
import org.hibernate.validator.internal.util.privilegedactions.GetConstructor;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Maintest {
public static void main(String[] args) {
opmanagerImpl xx = new opmanagerImpl();
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:META- INF/applicationContext1.xml");
opération op=new opération(15, 'f', 120, "bonjour", null, 12, 15);
xx.creerOpération(op);
//System.out.println("hiiiiiiiiiiii");
}
}
Results:
252 [main] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1b61d282: startup date [Sat May 03 02:43:19 CEST 2014]; root of context hierarchy
493 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5ab6e2e3: defining beans []; root of factory hierarchy
Exception in thread "main" java.lang.NullPointerException
at com.ensi.dao.opmanagerImpl.creerOpération(opmanagerImpl.java:19)
at com.ensi.dao.Maintest.main(Maintest.java:16) error `
T̶r̶y̶ ̶c̶h̶a̶n̶g̶i̶n̶g̶ ̶
̶#̶P̶e̶r̶s̶i̶s̶t̶e̶n̶c̶e̶C̶o̶n̶t̶e̶x̶t̶(̶u̶n̶i̶t̶N̶a̶m̶e̶=̶"̶E̶R̶P̶_̶P̶C̶D̶"̶)̶
̶p̶r̶i̶v̶a̶t̶e̶ ̶E̶n̶t̶i̶t̶y̶M̶a̶n̶a̶g̶e̶r̶ ̶e̶m̶;̶
T̶o̶
#̶A̶u̶t̶o̶w̶i̶r̶e̶d̶ ̶
p̶r̶i̶v̶a̶t̶e̶ ̶E̶n̶t̶i̶t̶y̶M̶a̶n̶a̶g̶e̶r̶ ̶e̶m̶;̶
The problem is that you're manually creating opmanagerImpl xx instance:
public static void main(String[] args) {
opmanagerImpl xx = new opmanagerImpl();
//rest of the code...
}
When using Spring, you should not create your beans manually, instead let Spring create them and obtain an instance of the bean through the application context. Change the code to:
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:META-INF/applicationContext1.xml");
opmanagerImpl xx = ctx.getBean("dao", opmanagerImpl .class);
opération op = new opération(15, 'f', 120, "bonjour", null, 12, 15);
xx.creerOpération(op);
//System.out.println("hiiiiiiiiiiii");
}

Categories

Resources