Spring Boot not Autowiring datasource to DAO - java

Good afternoon, I am experiencing an issue where my spring application is not autowiring a Datasource to a DAO. The database is a postgresql db being ran on my local machine. I'm getting a null pointer exception in my userDAO where we try to execute datasource.getConnection, which is the error being caused when a certain endpoint of the api is requested. In the DatabaseConfig class method postgresDatasource, there is a commented out try catch block where I see if we still get thrown a null pointer exception if we attempt ds.getConnection. It does not throw an exception in there, event though that code is being ran at server build. Like I said, the error gets thrown when I assume that the autowiring is being execute corrected and we try datasource.getConnection. All relevant code will be pasted below. first is the DatabaseConfig class. It may be worth noting that my DatabaseConfig is in com.example.config, and the DAO is in com.example.dao
#Configuration
#ComponentScan(basePackages="com.example")
public class DatabaseConfig {
#Bean
public DataSource postgresDataSource() {
final DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUrl("jdbc:postgresql://localhost:5432/postgres");
ds.setUsername("username");
ds.setPassword("password");
// System.out.println("Returning ds object after setting parameters");
// System.out.println(ds.toString());
// try {
// System.out.println("Attempting connection at server build.");
// ds.getConnection();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("DataSource postgresDataSource() is being ran");
return ds;
}
}
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.fmn.config.DatabaseConfig;
import com.fmn.dto.UserDTO;
#Repository
public class UserDAO {
// #Autowired
private DataSource datasource;
// #Autowired
// public void setDataSource(DataSource datasource) {
// this.datasource = datasource;
// }
//
#Autowired
public UserDAO(DataSource datasource){
System.out.println("Setting datasource in constructor");
this.datasource = datasource;
}
//
public UserDAO() {};
public boolean addUser(UserDTO user) {
//TODO: implement
return false;
}
public boolean updateUser(UserDTO user) {
//TODO: implement
return false;
}
public UserDTO getUserInfo(UserDTO user)/*throws UserNotFoundException*/ {
//TODO: implement
if(user.getUserId() != null) {
return getUserInfoWithUserID(user);
} else if (user.getEmail() != null) {
return getUserInfoWithEmail(user);
} else if (user.getPhoneNum() != null) {
return getUserInfoWithPhone(user);
}
//else throw new UserNotFoundException();
return null;
}
private UserDTO getUserInfoWithEmail(UserDTO user) {
//TODO: implement
return null;
}
private UserDTO getUserInfoWithPhone(UserDTO user) {
//TODO: implement
return null;
}
public UserDTO getUserInfoWithUserID(UserDTO user) {
UserDTO outUser = null;
ResultSet result = null;
Connection conn = null;
try {
// DatabaseConfig dbc = new DatabaseConfig();
// System.out.println("Setting datasource");
// datasource = dbc.postgresDataSource();
System.out.println("Calling datasource.getConnection()");
conn = datasource.getConnection();
CallableStatement caller = conn.prepareCall("{?= call get_user_info_with_userid(?)}");
caller.registerOutParameter(1, Types.REF_CURSOR);
caller.setString(2, user.getUserId());
caller.execute();
result = caller.getResultSet();
result.next();
outUser = setUserDTOFromResultSet(result);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outUser;
}
private UserDTO setUserDTOFromResultSet(ResultSet result) throws SQLException {
UserDTO outUser = new UserDTO();
outUser.setDOB(result.getDate("DOB"));
outUser.setUserId(result.getString("USER_ID"));
outUser.setfName(result.getString("F_NAME"));
outUser.setlName(result.getString("L_NAME"));
outUser.setEmail(result.getString("EMAIL"));
outUser.setAliveFlg(result.getString("ALIVE_FLG"));
return outUser;
}
}
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan(basePackageClasses = {DatabaseConfig.class, InteractiveController.class, UserDAO.class})
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(DatabaseConfig.class);
ctx.refresh();
SpringApplication.run(Application.class, args);
}
}
Your feedback and input is appreciated. Thank you!

Related

How do I test responses to successful and nonsuccessful database connections (JDBC)?

Below is code that I have. I've been trying different ways to test, including stubbing, mocking and spying. When I tried mocking the DriverManager.getConnection(), I got a message that it's private. I'm trying to practice TDD, so I know that it's not the intention to test the connection itself but rather the behavior surrounding the connection.
public class Main {
public static void main(String[] args) {
Datasource datasource = new Datasource();
if(datasource.open() == false){
return;
}
datasource.close();
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Datasource {
public static final String DB_NAME = "DBNAME";
public static final String DB_USERNAME = "USERNAME";
public static final String DB_PASSWORD = "PASSWORD";
public static final String SUBPROTOCOL = "jdbc:oracle:thin:#";
public static final String SERVER_NAME = "SERVERNAME";
public static final String PORT_NUMBER = "1521";
public static final String CONNECTION_STRING = SUBPROTOCOL + SERVER_NAME + ":" + PORT_NUMBER + "/" + DB_NAME;
private Connection conn;
public boolean open(){
try {
conn = DriverManager.getConnection(CONNECTION_STRING, DB_USERNAME, DB_PASSWORD);
System.out.println("Connected to database successfully.");
return true;
} catch (SQLException e) {
System.out.println("Error connecting to database: " + e.getMessage());
return false;
}
}
/**
* Closes the connection to the HR database.
* #return void
*/
public void close() {
try {
if (conn != null) {
conn.close();
System.out.println("Closed database connection successfully.");
}
} catch (SQLException e) {
System.out.println("Error closing database connection: " + e.getMessage());
}
}
}
import static org.junit.jupiter.api.Assertions.*;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Spy;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class DatasourceTest {
#Test
void exceptionIsThrownIfHRDatabaseConnectionFails() throws SQLException {
//Datasource testDatasource = new Datasource();
//assertThrows(SQLException.class, () -> {testDatasource.open();});
//TODO come back to this to mock connection
Datasource testDatasource = mock(Datasource.class);
DriverManager testDriverManager = mock(DriverManager.class);
when(testDriverManager.getConnection(Datasource.CONNECTION_STRING, Datasource.DB_USERNAME, Datasource.DB_PASSWORD)).thenReturn(null);
assertThrows(SQLException.class, () -> {testDatasource.open();});
}
#Test
void exceptionIsThrownIfConnectionIsNullDuringClose() throws SQLException {
Datasource testDatasource = new Datasource();
DriverManager testDriverManager = mock(DriverManager.class);
when(testDriverManager.getConnection(Datasource.CONNECTION_STRING, Datasource.DB_USERNAME, Datasource.DB_PASSWORD)).thenReturn(null);
}
}
Many developers may argue this test does not make sense, but in some cases you may want to test that a connection was successfully closed after using it (eg: if you find that a bug was happening because your program was exceeding the max number of connections for a giving resource, TDD encourages you to adding a test for this bugfix). In order to do this
Design the method interface by adding a test and make it fail (class DatasetTest.java):
public void whenDatasetClosed_closedReturnsTrue() {
//Arrange
//create a new dataset instance of your Dataset Class
Dataset dataset = new Dataset();
//Act
dataset.close();
//Assert
assertTrue(dataset.isClosed());
}
make conn an attribute of Dataset class
Implement close() method in Dataset class
Add the isClosed() method to the Dataset class exposing the connection status (eg. dataset.isClosed(), class Dataset.java).
public boolean isClosed() {
return this.conn.isClosed();
}
Repeat for the case where the connection is not closed and should return false.

Implementing HikariCP in Xpages Javabean breaking

I am implementing A Javabean SQL connection in Xpages. I am trying to create a connection pool for this Bean implementation using HikariCP.
Here is my code.
Datasource Class
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class HikariDS
{
private static DataSource datasource;
public static DataSource getDataSource(String jdbcURL, String user, String pass)
{
if(datasource == null)
{
try
{
HikariConfig config = new HikariConfig();
config.setJdbcUrl(jdbcURL);
config.setUsername(user);
config.setPassword(pass);
config.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
config.setMaximumPoolSize(100);
config.setAutoCommit(false);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
datasource = new HikariDataSource(config);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
return datasource;
}
}
SQL Connection bean
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.io.Serializable;
import com.sqlPoolConnect;
import javax.sql.DataSource;
public class sqlConnection implements Serializable
{
private static final long serialVersionUID = 1L;
private String query;
private String retError;
private String conString;
DataSource dataSource;
Connection con = null;
PreparedStatement prep = null;
private String USER;
private String PASS;
public sqlConnection()
{
}
public String getConString()
{
return conString;
}
public void setConString(String cS)
{
this.conString = cS;
}
public String getUSER()
{
return USER;
}
public void setUSER(String U)
{
this.USER = U;
}
public void setPASS(String P)
{
this.PASS = P;
}
public String getPASS()
{
return PASS;
}
public String getQuery()
{
return query;
}
public void setQuery(String query)
{
this.query = query;
}
public void execQuery()
{
con = null;
prep = null;
try
{
dataSource = sqlPoolConnect.getDataSource(getConString(), getUSER(), getPASS());
con = dataSource.getConnection();
prep = con.prepareStatement(getQuery());
prep.executeQuery();
}
catch(Exception sqlex)
{
sqlex.printStackTrace();
}
finally
{
try
{
if(prep != null)
{
prep.close();
}
con.rollback();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
SSJS Call of Bean
function testInsert(inCon)
{
var query = "INSERT INTO table_name
(1,2,3,4,5) ";
sqlConnection.setUSER("USER");
sqlConnection.setPass("PASS");
sqlConnection.setConString(inCon);
sqlConnection.setQuery(query);
sqlConnection.execQuery();
}
When the bean is invoked. IT BREAKS AT HikariConfig config = new HikariConfig(); in the KikaryDS Class.
Please advise if anyone knows why it will break over there.
Edit:
I ran the code in a separate java project and received this error.
Exception in thread "main" java.lang.NoClassDefFoundError: com.zaxxer.hikari.HikariConfig
at HikariCP.getDataSource(HikariCP.java:20)
at HikariCP.main(HikariCP.java:45)
Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariConfig
at java.net.URLClassLoader.findClass(URLClassLoader.java:609)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:925)
at java.lang.ClassLoader.loadClass(ClassLoader.java:870)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:343)
at java.lang.ClassLoader.loadClass(ClassLoader.java:853)
... 2 more
MANIFEST.MF
Manifest-Version: 1.0
Bnd-LastModified: 1588952278176
Build-Jdk: 11.0.2
Built-By: brettw
Bundle-Description: Ultimate JDBC Connection Pool
Bundle-DocURL: https://github.com/brettwooldridge
Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt
Bundle-ManifestVersion: 2
Bundle-Name: HikariCP
Bundle-SymbolicName: com.zaxxer.HikariCP
Bundle-Vendor: Zaxxer.com
Bundle-Version: 3.4.5
Created-By: Apache Maven Bundle Plugin
DynamicImport-Package: *
Export-Package: com.zaxxer.hikari;version="3.4.5";uses:="com.zaxxer.hi
kari.metrics,javax.naming,javax.naming.spi,javax.sql",com.zaxxer.hika
ri.hibernate;version="3.4.5";uses:="com.zaxxer.hikari,org.hibernate,o
rg.hibernate.engine.jdbc.connections.spi,org.hibernate.service.spi",c
om.zaxxer.hikari.metrics;version="3.4.5",com.zaxxer.hikari.pool;versi
on="3.4.5";uses:="com.zaxxer.hikari,com.zaxxer.hikari.metrics,com.zax
xer.hikari.util,javax.sql",com.zaxxer.hikari.util;version="3.4.5";use
s:="javax.sql"
Import-Package: javax.management,javax.naming,javax.naming.spi,javax.s
ql,com.codahale.metrics;resolution:=optional;version="[3.2,4)",com.co
dahale.metrics.health;resolution:=optional;version="[3.2,4)",io.micro
meter.core.instrument;resolution:=optional,org.slf4j;version="[1.6,2)
",org.hibernate;resolution:=optional;version="[5.2,6)",org.hibernate.
engine.jdbc.connections.spi;resolution:=optional;version="[5.2,6)",or
g.hibernate.service;resolution:=optional;version="[5.2,6)",org.hibern
ate.service.spi;resolution:=optional;version="[5.2,6)",javax.sql.rows
et,javax.sql.rowset.serial,javax.sql.rowset.spi,org.hibernate.cfg;res
olution:=optional;version="[5.2,6)"
Multi-Release: true
Originally-Created-By: Apache Maven Bundle Plugin
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.8))"
Tool: Bnd-4.2.0.201903051501
I have imported HikariCP-3.4.5.jar and slf4j-simple-1.7.30.jar and have ensured it is in my Java Build Path. What else could be causing this issue?

How can I integrate Spring Boot with Hibernate?

package com.batch.hibernate.config;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.skip.SkipPolicy;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.LineMapper;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.LineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.batch.hibernate.job.FileVerificationSkipper;
import com.batch.hibernate.job.UserItemPreparedStatementSetter;
import com.batch.hibernate.job.UserItemProcessor;
import com.batch.hibernate.model.User;
#Configuration
#EnableBatchProcessing
/*#ComponentScan(basePackages = { "com.batch.hibernate" })
#PropertySource("classpath:application.properties")*/
public class BatchConfiguration {
#Autowired
private Environment environment;
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
public DataSource dataSource;
#Bean
public DataSource dataSource(){
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getProperty("connection.driver_class"));
dataSource.setUrl(environment.getProperty("connection.url"));
dataSource.setUsername(environment.getProperty("connection.username"));
dataSource.setPassword(environment.getProperty("connection.password"));
return dataSource;
}
#Bean
public FlatFileItemReader<User> reader(){
FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
reader.setResource(new FileSystemResource(environment.getProperty("local.filesystem.path")));
reader.setLinesToSkip(Integer.valueOf(environment.getProperty("header.lines.in.file")));
LineMapper<User> userLineMapper = createUserLineMapper();
reader.setLineMapper(userLineMapper);
return reader;
}
private LineMapper<User> createUserLineMapper() {
DefaultLineMapper<User> userLineMapper = new DefaultLineMapper<>();
LineTokenizer userLineTokenizer = createUserLineTokenizer();
userLineMapper.setLineTokenizer(userLineTokenizer);
FieldSetMapper<User> userInformationMapper = createUserInformationMapper();
userLineMapper.setFieldSetMapper(userInformationMapper);
return userLineMapper;
}
private LineTokenizer createUserLineTokenizer() {
DelimitedLineTokenizer userLineTokenizer = new DelimitedLineTokenizer();
userLineTokenizer.setDelimiter(environment.getProperty("column.delimiter"));
userLineTokenizer.setNames(environment.getProperty("column.names").split(","));
return userLineTokenizer;
}
private FieldSetMapper<User> createUserInformationMapper() {
BeanWrapperFieldSetMapper<User> userInformationMapper = new BeanWrapperFieldSetMapper<>();
userInformationMapper.setTargetType(User.class);
return userInformationMapper;
}
#Bean
public UserItemProcessor processor(){
return new UserItemProcessor();
}
#Bean
public JdbcBatchItemWriter<User> writer(){
JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>();
writer.setDataSource(dataSource);
writer.setSql("INSERT INTO user (name, id) VALUES (?,?)");
writer.setItemPreparedStatementSetter(new UserItemPreparedStatementSetter());
return writer;
}
#Bean
public Step step1(){
return stepBuilderFactory.get("step1")
.<User, User> chunk(10000)
.reader(reader())
.faultTolerant()
.skipPolicy(fileVerificationSkipper())
.processor(processor())
.writer(writer())
.build();
}
#Bean
public Job importUserJob(){
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.flow(step1())
.end()
.build();
}
#Bean
public SkipPolicy fileVerificationSkipper() {
return new FileVerificationSkipper();
}
/*#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}*/
}
and my HibernateUtil.java is:
package com.batch.hibernate.util;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.batch.hibernate.model.User;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SpringBatchUtil springBatchUtil;
private static Properties properties;
public static SessionFactory buildSessionFactory() {
SessionFactory localSessionFactory = null;
springBatchUtil = new SpringBatchUtil();
try {
Configuration configuration = new Configuration();
properties = springBatchUtil.loadProperties();
configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_URL,
properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_URL));
configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_USERNAME,
properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_USERNAME));
configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_PASSWORD,
properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_PASSWORD));
configuration.setProperty(SpringBatchConstants.HIBERNATE_SHOW_SQL,
properties.getProperty(SpringBatchConstants.HIBERNATE_SHOW_SQL));
configuration.setProperty(SpringBatchConstants.HIBERNATE_CURRENT_SESSION_CONTEXT_CLASS,
properties.getProperty(SpringBatchConstants.HIBERNATE_CURRENT_SESSION_CONTEXT_CLASS));
configuration.setProperty(SpringBatchConstants.HIBERNATE_CONNECTION_DRIVER_CLASS,
properties.getProperty(SpringBatchConstants.HIBERNATE_CONNECTION_DRIVER_CLASS));
configuration.addPackage("com.batch.hibernate.model");
configuration.addAnnotatedClass(User.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
localSessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (HibernateException he) {
he.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return localSessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() throws Exception {
if (getSessionFactory() == null) {
throw new HibernateException("Initial SessionFactory creation failed.");
}
Session session = getSessionFactory().getCurrentSession();
session.getTransaction().begin();
return session;
}
public static void closeSession(Session session) {
if (session != null) {
if (session.getTransaction().isActive()) {
session.getTransaction().commit();
}
session.close();
}
}
}
I have dataSource settings and hibernateUtil as above, I want to use hibernate rather than JDBC while configuring dataSource.
The prime reason to integrate with hibernate is for auditing purpose while writing records from file to database.
How can I use hibernate here in this context? or Is there a way to audit using the way I am already using?
Sorry if i am not clear with my question.
Have a look at Spring-starter-data-jpa. Set the needed properties like hibernate.dialect etc, and you don't need to do anything yourself, it works o.o.t.b.
Spring data jpa should be enough to solve all your issues.
Please look at this Repo for starter guide .
https://github.com/rahulrsingh09/Spring-Boot-DataJPA

Full RESTFUL WebService with GSON and Java

I have created a RESTFUL webservice, witch returns a json, but at this time i only consult and show a simple select * , i need to create a complete CRUD solution, if anyone have some samples to share, i'll appreciate.
Best Regards to all
My code until now are:
DAO - Access.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.Usuarios;
public class Access
{
public ArrayList<Usuarios> getUsuarios(Connection con) throws SQLException
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM usuarios");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Usuarios usuariosObj = new Usuarios();
usuariosObj.setUsr_id(rs.getInt("usr_id"));
usuariosObj.setUsr_login(rs.getString("usr_login"));
usuariosObj.setUsr_pwd(rs.getString("usr_pwd"));
usuariosList.add(usuariosObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return usuariosList;
}
}
DTO - Usuarios.java
package dto;
public class Usuarios
{
private int usr_id;
private String usr_login;
private String usr_pwd;
public Usuarios()
{
}
public Usuarios(int usr_id, String usr_login, String usr_pwd)
{
super();
this.usr_id = usr_id;
this.usr_login = usr_login;
this.usr_pwd = usr_pwd;
}
public int getUsr_id()
{
return usr_id;
}
public void setUsr_id(int usr_id)
{
this.usr_id = usr_id;
}
public String getUsr_login()
{
return usr_login;
}
public void setUsr_login(String usr_login)
{
this.usr_login = usr_login;
}
public String getUsr_pwd()
{
return usr_pwd;
}
public void setUsr_pwd(String usr_pwd)
{
this.usr_pwd = usr_pwd;
}
#Override
public String toString()
{
return "[ {usr_id=" + usr_id + ", usr_login=" + usr_login + ", usr_pwd=" + usr_pwd + "} ]";
}
}
Model - AccessManager.java
package model;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import dao.Access;
import dao.Database;
import dto.Usuarios;
public class AccessManager
{
public ArrayList<Usuarios> getUsuarios() throws Exception
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
usuariosList = access.getUsuarios(con);
return usuariosList;
}
}
WebService - UsuariosService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.google.gson.Gson;
import model.AccessManager;
import dto.Usuarios;
#Path("/UsuariosService")
public class UsuariosService
{
#GET
#Path("/usuarios")
#Produces("application/json")
public String usuarios()
{
String usuarios = null;
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
try
{
usuariosList = new AccessManager().getUsuarios();
Gson gson = new Gson();
//usuarios = gson.toJson(usuariosList);
usuarios = "{\"usuarios\" :" + gson.toJson(usuariosList) + "}";
} catch (Exception e)
{
e.printStackTrace();
}
return usuarios;
}
}
Usually you should ask a specific trouble you have instead of ask for samples. It looks like you have a structured code and all you need is implement all operations exposing as a service.
In case you need a sample, there quite a lot of resources on the web. Something like this: https://code.google.com/p/javaee6-crud-example/
I'll try give you some quick tips below:
WebService - UsuariosService.java
#POST
#Path("/usuarios")
public Response save(Usuario user) {
try {
manager= new AccessManager();
manager.save(user);
return Response.ok("User has been created.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#DELETE
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id) {
try {
manager= new AccessManager();
manager.delete(id);
return Response.ok("User has been deleted.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#PUT
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id, Usuario user) {
try {
manager= new AccessManager();
manager.update(id, user);
return Response.ok("User has been updated.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
If you donĀ“t understand the usage of PUT, DELETE, POST and so on, I recommend you to read HTTP Method Tutorial. There is several discussion regarding this but you might skip it for a while.
I think you might get an idea from here. Your DAO needs to implement methods to perform CRUD interface as well. The link I've added has a very simple sample that might help as well. You might also check this JPA link.
Not sure whether info above helped but I think it is a start since you have to code it in order to understand more about it :)

instantiate JPA controller by injecting from glassfish

How do I actually instantiate the JPA controller below?
I'm fuzzy on how a Netbeans created JPA controller is actually used. I certainly appreciate the Netbeans wizard in this case, it's interesting -- I'm trying to understand how it works and why it works this way.
The ejb module can just inject from Glassfish along these lines:
#PersistenceUnit(unitName="JSFPU") //inject from your application server
EntityManagerFactory emf;
#Resource //inject from your application server
UserTransaction utx;
and then, to instantiate the controller, something like this:
PersonEntityJpaController pejc = new PersonEntityJpaController(utx, emf); //create an instance of your jpa controller and pass in the injected emf and utx
try {
pejc.create(pe); //persist the entity
Where can I find more information about how to inject the PU from, in this case, Glassfish, as well as how #Resource works? I don't at all mind reading Glassfish for JavaEE docs from Oracle, or other reference material.
The controller Netbeans generated:
package db;
import db.exceptions.NonexistentEntityException;
import db.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
public class ClientsJpaController implements Serializable {
public ClientsJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Clients clients) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(clients);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Clients clients) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
clients = em.merge(clients);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = clients.getId();
if (findClients(id) == null) {
throw new NonexistentEntityException("The clients with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Clients clients;
try {
clients = em.getReference(Clients.class, id);
clients.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The clients with id " + id + " no longer exists.", enfe);
}
em.remove(clients);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Clients> findClientsEntities() {
return findClientsEntities(true, -1, -1);
}
public List<Clients> findClientsEntities(int maxResults, int firstResult) {
return findClientsEntities(false, maxResults, firstResult);
}
private List<Clients> findClientsEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Clients.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Clients findClients(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Clients.class, id);
} finally {
em.close();
}
}
public int getClientsCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Clients> rt = cq.from(Clients.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
the class which will create and call methods on the controller; it is intended to provide a single queue for the web module to pop elements (in this, int's) from:
package db;
import javax.ejb.Singleton;
#Singleton
public class MySingletonQueue implements RemoteQueue {
private int next = 3; //dummy
private ClientsJpaController cjc; //instantiate how?
#Override
public int getNext() {
return next; //get next int from perhaps another class or method...
}
}
for context, the bean which the web page instantiates with EL:
package dur;
import db.RemoteQueue;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class MySessionBean implements Serializable {
#EJB
private RemoteQueue mySingletonQueue;
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(MySessionBean.class.getName());
public MySessionBean() {
}
public int getNext() {
log.info("getting next int from remote EJB");
return mySingletonQueue.getNext();
}
}
http://forums.netbeans.org/viewtopic.php?t=47442&highlight=jpa+controller+constructor
Answer is simple:
package db;
import javax.ejb.Singleton;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
#Singleton
public class MySingletonQueue implements RemoteQueue {
private int next = 3;
private ClientsJpaController cjc;
#PersistenceUnit
private EntityManagerFactory emf;
#Resource
private UserTransaction utx;
#PostConstruct
public void initBean() {
// Instantiate your controller here
cjc = new ClientsJpaController(utx, emf);
}
// rest of the class ...
}
But keep in mind that although it will work, what you are doing is extremely messy and unmaintainable and is considered a bad practice.
Update
Some advice:
You should inject an entity manager to your ClientsJpaController (also consider renaming it to ClientDAO)
Do not manage transactions in a server environment, lets server do that. Your code would be simplified to just a few lines.
Your entity Clients is in plural form, it should be singular because it represents single client, doesn't it?
You definitely should not do something like: catch (Exception ex) {, because it is a root of all exceptions. Catch only the most specific exception instead.
So, for example, your edit function can be shortened to:
public Client edit(Client client) {
return em.merge(client);
}
You should definitely take a look at some EJB/ JPA book or read some decent guide.

Categories

Resources