I'm learning JPAContainer, and I can't understand how to configure my SGBD connection...Using DAO mode I create an class that return my connection.
//ConnectionFactory DAO mode
public class ConnectionFactory {
public Connection getConnection() {
try {
return DriverManager.getConnection(
"jdbc:mysql://localhost/fj21", "root", "");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
How to create connection for to use with JPAContainer ? What better way ?
To start define your jpa persistence unit, lets say "addressbook". Then you could create a new JPAContainer using the JPAContainerFactory.
Example:
JPAContainerFactory.make(Person.class, JpaAddressbookApplication.PERSISTENCE_UNIT); // where PERSISTENCE_UNIT = "addressbook"
Going this way you don't have to deal with the EntityManager.
I highly recommend you to follow up this tutorial and have a look at the following answer on stackoverflow: https://stackoverflow.com/a/17876743
Related
I'm learning about JDBC and I have learned the steps: open connection, execute statement, get result, etc. I know about Connection, Statements and the other interfaces, but I just found a tutorial with another class, the Connector class. And I don't understand what exactly we can do with this Connector class. I have made some app without this class and I don't understand why do I need the Connector class? Any feedback will be apreciated!
Here is the code:
public Set getAllUsers() {
Connector connector = new Connector();
Connection connection = connector.getConnection();
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM user");
Set users = new HashSet();
while(rs.next())
{
User user = extractUserFromResultSet(rs);
users.add(user);
}
return users;
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
UPDATE:
This is the link where you can find the entire code: https://dzone.com/articles/building-simple-data-access-layer-using-jdbc
Your Connector is probably a class with a factory method:
the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.
Basically it is a utility class to create a Connection hiding the complexity of connection creation.
I am using the c3p0 library as my datasource object.
I want to create a JDBC helper class that helps reduce the boilerplate code that JDBC has and I am wondering if my implementation is correct and are following best practices? Also, if there is an already existing library that provides these functionalities, like QueryRunner, maybe?
Most of my queries returns a list of results of a specified column. Will it be okay if I use the following helper method for all my queries?
public List<String> retrieveSQLQuery(String sqlQuery, String column) {
List<String> values = new ArrayList<>();
try (Connection conn = getConnection();
PreparedStatement statement = conn.prepareStatement(sqlQuery);
ResultSet rs = statement.executeQuery(sqlQuery)) {
while (rs.next()) {
values.add(rs.getString(column));
}
} catch (SQLException e) {
e.printStackTrace();
}
return values;
}
The getConnection() method lives in a JDBCUtil class which provides the connection to the datasource object. This helper class will be extending JDBCUtil thus why it has access to that method.
I also know that frameworks like spring and Hibernate provide utilities, however, those frameworks are too large for my project.
I am designing a MVC JAVAFX program that has intensive database connection. I dont know where to put the database connection details. Whether I should define the connection details info in a Model form and process the connection as a controller or should I put them together in one single model file.
In the long run I need that connection as a session throughout the program until the user logoff.
Is there any simple example that I could study for this matter. I know using hibernate is the best way but im still learning Java FX and I need someguidance about this.
Thanks.
At the moment I'm also at an JavaFX application with an database connection. The way I chose is the following: Create a SQL-Controller-Class. This class should contain everything handling your SQL-Data(For example: a connect-method to open a connection - a close-method is also not wrong). Use this class in all your controller classes to get the data you need or save the data you have.
Here an little example
The SQLController class could look like that:
public class SqlController {
//Put you connection string with pw, user, ... here
private static final String YOUR_CONNECTION_STRING = "";
public boolean openConnection() {
boolean result;
try {
// Open your connection
result = true;
} catch (Exception e) {
result = false;
}
return result;
}
public boolean closeConnection() {
boolean result;
try {
// Close your connection
result = true;
} catch (Exception e) {
result = false;
}
return result;
}
public YourData getSomeData(){
//get The Data you want.
return YourData;
}
}
You could use the controller in any method of your UI-Controller.
public void handelSomeUiThing()
{
SqlController sc = new SqlController();
sc.openConnection();
YourData = sc.getSomeData();
sc.closeConnection();
}
Hope that helps!
PS: Everyone has his own programming-style. You have to see what fits for your application and what is the most comfortable way for you.
If you're using MVC, download the Spring Boot dependency and put it in your application.properties...
I am using Vaadin framework and following MVC design pattern to develop a web application project.
While implementing connection pooling feature for my project I encountered the following problem.
I am getting the ResultSet in one class(data class) and I am using that ResultSet in another class(Business Logic).
I have to close the connection object after using that ResultSet in the business logic class.
What may be the efficient way to achieve this without passing the connection object to the business logic class?
Please Explain.Thank You.
I would recommend that you write a Dao which returns a List of Business Objects and NOT the resultsets. The connection must be closed in the Dao itself. Below is an example
public class PersonDao {
private DataSource ds; //add a setter and inject the JDBC resource
public List<Person> getPersons() {
List<Person> personList = new ArrayList();
Connection con;
PreparedStatement pstmt;
try {
con = ds.getConnection(username, password);
pstmt = con.prepareStatement("SELECT * FROM PERSON");
ResultSet rs = pstmt.executeQuery(query);
//Fetch the resultset, iterate over it and populate the list
while (rs.next()) {
Person p = new Person();
p.setName(rs.getString("name");
personList.add(p);
}
} catch (Exception ex {
// ... code to handle exceptions
} finally {
if (con != null) con.close();
}
return personList;
}
If you can use Java 7, you can also use try with resource which would automatically handle the closing of connections for you. If you are not in a position to change the Dao interface, then it is a good idea to write a layer between the Dao and the business layer.
Does anyone have examples of how to use DBMS_APPLICATION_INFO package with JBOSS?
We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.
I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.
Has anyone done this before?
If you are using JBoss, you can use a "valid-connection-checker".
This class is normaly used to check the validity of the Connection.
But, as it will be invoked every time the Connection pool gives the user a Connection, you can use it to set the DBMS_ APPLICATION _INFO.
You declare such a class in the oracle-ds.xml like this:
<local-tx-datasource>
<jndi-name>jdbc/myDS</jndi-name>
<connection-url>jdbc:oracle:thin:#10.10.1.15:1521:SID</connection-url>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<security-domain>MyEncryptDBPassword</security-domain>
<valid-connection-checker-class-name>test.MyValidConn</valid-connection-checker-class-name>
<metadata>
<type-mapping>Oracle9i</type-mapping>
</metadata>
</local-tx-datasource>
Your class must implement the org.jboss.resource.adapter.jdbc.ValidConnectionChecker interface.
If you use Maven, you can include this interface with the following dependency:
<dependency>
<groupId>jboss</groupId>
<artifactId>jboss-common-jdbc-wrapper</artifactId>
<version>3.2.3</version>
<scope>provided</scope>
</dependency>
This interface has only one method: isValidConnection.
I copy my implementation:
public SQLException isValidConnection(Connection arg0) {
CallableStatement statement;
try {
statement = arg0.prepareCall("call dbms_application_info.set_client_info('"+getInfos()+"')");
statement.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Hope it helps !
BenoƮt
yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
OracleConnection conn=connectionPool.getConnection("java:scott#mydb");
Change it to:
public class LoggingConnectionPool extends ConnectionPool{
public OracleConnection getConnection(String datasourceName, String module, String action){
OracleConnection conn=getConnection(datasourceName);
CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setString(1,module);
call.setString(2,action);
call.execute();
finally{
call.close();
}
return new WrappedOracleConnection(conn);
}
Note the use of WrappedOracleConnection above. You need this because you need to trap the close call
public class WrappedOracleConnection extends OracleConnection{
public void close(){
CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setNull(1,Types.VARCHAR);
call.setNull(2,Types.VARCHAR);
call.execute();
finally{
call.close();
}
}
// and you need to implement every other method
//for example
public CallableStatement prepareCall(String command){
return super.prepareCall(command);
}
...
}
Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool).
In your -ds.xml, you can set a connection property called v$session.program and the value of that property will populate the PROGRAM column of each session in the V$SESSION view created for connections originating from your connection pool. I usually set it to the jboss.server.name property.
See here for an example.