Class for manipulating with table in DB- Java MySQL - java

I should make separate class with reading library of books, updating etc.
Class books should have:
parametric constructor plus override for toString()
Method getAll static to read all data for DB
Method getById is reading data when we give ID, also static.
but i did next:
Main.java
try {
ArrayList<String[]> allBooks = Books.getAll("SELECT * FROM books");
for (String[] izd : allBooks) {
System.out.println("Books id: " + izd[0] + " Date of publishing: " + izd[1] + " Id of books: " + izd[2]+...);
}
} catch (Exception e) {
System.out.println(e);
}
Books.java
static ArrayList<String[]> getAll(String stt) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException
{
connect();
Statement stmt = conn.createStatement();
stmt.executeQuery(stt);
ResultSet rs = stmt.getResultSet();
int columnsNum = rs.getMetaData().getColumnCount();
ArrayList<String[]> result = new ArrayList<String[]>();
while(rs.next())
{
String[] rowArr = new String[columnsNum];
for(int i=0;i<columnsNum;i++)
rowArr[i]=rs.getString(i+1).toString();
result.add(rowArr);
}
close();
return result;
}
I really don't understand how.. Any help will be like :D

You are not really giving much information about your goal here, so I can only guess. I would expect something like this:
public class Book {
private String title;
//...
//constructor
public Book(String theTitle) {
this.title = theTitle;
}
public static ArrayList<Book> getAll(String stt) { /* ... */ }
public static Book getById(int id) { /* ... */ }
}
And in your getAll function you probably want something like this:
while(rs.next())
{
Book aBook = new Book(rs.getString("title"));
result.add(aBook);
}

Related

How to unit test ResultSetExtractor?

I need advice on how to unit test a ResultSetExtractor when using jdbc.
String sql = "SELECT * FROM item where item_id = ?";
return (Item) jdbcTemplate.query(sql, new ResultSetExtractor<Item>() {
#Override
public Item extractData(final ResultSet rs) throws ... {
if (rs.next()) {
Item item = new Item (rs.getString(1), rs.getString(2));
return item ;
} else
return null;
}
}, itemId);
}
With the above approach of using an anonymous class, I would have to use argumentCaptor to get the ResultSetExtractor. The test I have so far is below. I don't know how what to do next in terms of the ResultSetExtractor.
#Test
public void testGetItemByID() {
ArgumentCaptor<ResultSetExtractor> rseCaptor = ArgumentCaptor.forClass(ResultSetExtractor.class);
ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
String sql = "SELECT * FROM item where item_id = ?";
itemDAOImpl.getItemByID(testId);
verify(mockJdbcTemplate, times(1)).query(stringCaptor.capture(), rseCaptor.capture(), stringCaptor.capture());
assertEquals(stringCaptor.getAllValues().get(0),sql);
assertEquals(stringCaptor.getAllValues().get(1),testId);
}
I dont know if using an anonymous class would make it harder to unit test. I could always pull the anonymous class out of the jdbc call and make a class like below, but I dont know where to start testing this class.
public class ItemResultSet implements ResultSetExtractor<Item> {
#Override
public Item extractData(ResultSet rs) throws ...{
if (rs.next()) {
Item item = new Item (rs.getString(1), rs.getString(2));
return item ;
} else
return null;
}
}
The test below would pass with either implementations but I want to avoid using any(ResultSetExtractor.class). What I want is to test the actual implementation of extractData(final ResultSet rs) if possible.
#Test
public void testGetItemByID() {
String sql = "SELECT * FROM item where item_id = ?";
when(mockJdbcTemplate.query(anyString(), any(ResultSetExtractor.class), anyString()))
.thenReturn(testItem);
assertEquals(testItem, itemDAOImpl.getItemByID(testId));
}
You could do the following
private ResultSet getMockResultSet() throws Exception {
ResultSet rs = Mockito.mock(ResultSet.class);
Mockito.when(rs.next()).thenReturn(true).thenReturn(false);
Mockito.when(rs.getString(1)).thenReturn("Value 1");
Mockito.when(rs.getString(2)).thenReturn("Value 2");
return rs;
}
private ResultSet getEmptyMockResultSet() throws Exception {
ResultSet rs = Mockito.mock(ResultSet.class);
Mockito.when(rs.next()).thenReturn(false);
return rs;
}
#Test
public void testDataExists() {
Item item = new ResultSetExtractor<Item>() {
#Override
public Item extractData(final ResultSet rs) throws ... {
if (rs.next()) {
Item item = new Item (rs.getString(1), rs.getString(2));
return item ;
} else
return null;
}
}.extractDatae(getMockResultSet());
assertEquals(item.getFirst(), "Value 1");
assertEquals(item.getSecond(), "Value 2");
}
#Test
public void testNoDataExists() {
Item item = new ResultSetExtractor<Item>() {
#Override
public Item extractData(final ResultSet rs) throws ... {
if (rs.next()) {
Item item = new Item (rs.getString(1), rs.getString(2));
return item ;
} else
return null;
}
}.extractData(getEmptyMockResultSet());
assertNull(item);
}

BeanUtils.setProperty method sets null a BigDecimal field

I'm having a problem using the BeanUtils.setProperty method.
I'm using this JAR:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
I run a MySQL query that returns one record and I'm mapping the resultset to a JavaBean that I've made.
Here you have the main class.
public class QueryTester {
public static void viewTable(Connection con) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
Statement stmt = null;
String query = "SELECT * FROM Books WHERE code = 'AA00'";
try {
stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMapper<Books> rsMapper = new ResultSetMapper<Books>();
List<Books> list = rsMapper.mapResultSetToObject(rs, Books.class);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost/dbname";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = (Connection) DriverManager.getConnection(url,userName,password);
viewTable(conn);
conn.close();
} catch (Exception e) {
System.out.println("NO CONNECTION");
}
}
}
And this is the method that uses the BeanUtils.setProperty method.
public class ResultSetMapper<T> {
public List<T> mapResultSetToObject(ResultSet rs, Class<T> outputClass) throws InstantiationException, SQLException, IllegalAccessException, InvocationTargetException {
List<T> outputList = new ArrayList<T>();
if (rs == null) {
return outputList;
}
if (!outputClass.isAnnotationPresent(Entity.class)) {
throw new InstantiationException("Entity notation not present.");
}
ResultSetMetaData rsmd = rs.getMetaData();
// retrieve data fields from output class
Field[] fields = outputClass.getDeclaredFields();
while (rs.next()) {
T bean = (T) outputClass.newInstance();
for (int iterator = 0; iterator < rsmd.getColumnCount(); iterator++) {
String columnName = rsmd.getColumnName(iterator + 1);
Object columnValue = rs.getObject(iterator + 1);
for (Field field : fields) {
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
if (column.name().equalsIgnoreCase(columnName) && columnValue != null) {
BeanUtils.setProperty(bean, field.getName(), columnValue);
break;
}
}
}
}
outputList.add(bean);
}
return outputList;
}
}
mapResultSetToObject method returns a List with one element that is correct but the bean is set in a wrong way.
The fields code and bookDescription are set right but kPrice field is set null instead of 3.000 that is the value from database.
I run this code in debug mode and "columnValue" variable's value is 3.000 but the setProperty method doesn't set the right value and the value remains null.
Here you have my Java Bean.
#Entity
public class Books {
#Column(name="code")
private String code;
#Column(name="book_description")
private String bookDescription;
#Column(name="kPrice")
private BigDecimal kPrice;
public Books() {}
public Books(String code, String bookDescription, BigDecimal kPrice){
this.code = code;
this.bookDescription = bookDescription;
this.kPrice = kPrice;
}
/* Getters and setters */
...
}
And this is the MySQL table and the record.
CREATE TABLE `Books` (
`code` varchar(4) NOT NULL,
`book_description` varchar(50) NOT NULL DEFAULT '',
`kPrice` decimal(10,4) NOT NULL DEFAULT '1.0000',
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO dbname.Books (code, book_description, kPrice) VALUES('AA00', 'Description example', 3.0000);
Why I get this behaviour? What am I missing?
Thanks in advance
Are you sure which the name of setters/getters is the same of property?
In some case, the problem is that.
See my example below:
#Entity
public class Books {
#Column(name="code")
private String code;
#Column(name="book_description")
private String bookDescription;
#Column(name="kPrice")
private BigDecimal kPrice;
public Books() {}
public Books(String code, String bookDescription, BigDecimal kPrice){
this.code = code;
this.bookDescription = bookDescription;
this.kPrice = kPrice;
}
public void setKPrice ( Bigdecimal kPrice) // and not setkPrice or setPrice..
{
this.kPrice = kPrice;
}
public BigDecimal getKPrice () // and not getkPrice or getPrice..
{
return this.kPrice;
}
}

Convert a parameter according to Database in Java Spring

Here i got value for catname from parameter as movie but in database its have corresponding value as 1, same for music->2, game->3....
"WHERE (\n" +
"\t\t(`Post`.`status` = 1)\n" +
"\t\tAND (`Post`.`postto_id` =\"+catname+\" \")\n" +
"\t\t)" +
"ORDER BY `Post`.`id` desc LIMIT 5", new CrelistMapper());
} catch (Exception e) {
throw e;
}
}
private class CrelistMapper implements ResultSetExtractor<List<Creativity>> {
public List<Creativity> extractData(ResultSet resultSet) throws SQLException {
List<Creativity> crelistList = new ArrayList<Creativity>();
while (resultSet.next()) {
Creativity userObject = new Creativity(resultSet.getString("**postto_id**"),
Here i got value as movie in "postto_id" how can i convert it into 1 instead of movies from parameter?
I believe you are looking for parse int from Integer class.
import java.lang.Integer;
public class test{
public static void main(String[] args){
String stringId = "1";
int intFromString = Integer.parseInt(stringId);
System.out.println(intFromString);
}
}
Look here for a version of the overloaded method that meets your purpose

Working with ResultSets in Java

I've ran into a problem of having to run a number of different queries on the DB (different return types, different number of columns, etc).
While writing that i started to wonder if there's a proper way of writing a helper function.
It seemed that it's really easy to write a function that returns a ResultSet.
However since it a) doesn't close connection b) doesn't close the result set it seems as a possibly working, but improper solution. Is there any place to dump in all results so that they can be returned safely.
(Only thing i could come up with, is just returning a 2D string array (after converting all data to strings) and then converting it all back)
EDIT : Sorry for not writing clear, was wondering if there's any way to just store the result of the query as is (don't need to modify it) without writing a separate method for every possible return type.
The idea behind a 2d string list is being able to store the query values as is.
Col1 Row1 | Col2 Row1 | Col3 Row1
Col1 Row2 | Col2 Row2 | Col3 Row2
EDIT 2 Thank you for replies, i guess i'll just write a small parser for it.
You shouldn't be returning resultSets, you should read the results from the resultset into some kind of container object. A ResultSet is a wrapper around a database cursor, it goes away when the connection closes. It's something you read from and close right away, not something you can pass around your application.
Look at how spring-jdbc does it. You implement a resultSetMapper that is passed to the method on the JdbcTemplate.
Several observations:
You don't need to use Spring to use spring-jdbc. However, I see very little value in reimplementing this stuff yourself.
It's not the job of the code that reads the ResultSet to open and close connections, that needs to be elsewhere.
I'd recommend looking at Spring JDBC. Don't write such a thing yourself. It's already been done, and quite well.
For example, I don't like your idea of returning a List of Strings. You lose a lot of info that way. I'd return a Map of Lists (column view) or List of Maps (row view).
If you must, here are some database utilities that would get you started.
package persistence;
import java.sql.*;
import java.util.*;
/**
* util.DatabaseUtils
* User: Michael
* Date: Aug 17, 2010
* Time: 7:58:02 PM
*/
public class DatabaseUtils {
/*
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#host:1521:database";
private static final String DEFAULT_USERNAME = "username";
private static final String DEFAULT_PASSWORD = "password";
*/
/*
private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
private static final String DEFAULT_USERNAME = "pgsuper";
private static final String DEFAULT_PASSWORD = "pgsuper";
*/
private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
private static final String DEFAULT_USERNAME = "party";
private static final String DEFAULT_PASSWORD = "party";
public static void main(String[] args) {
long begTime = System.currentTimeMillis();
String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);
Connection connection = null;
try {
connection = createConnection(driver, url, username, password);
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDatabaseProductVersion());
String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
connection.setAutoCommit(false);
String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
List parameters = Arrays.asList("Foo", "Bar");
int numRowsUpdated = update(connection, sqlUpdate, parameters);
connection.commit();
System.out.println("# rows inserted: " + numRowsUpdated);
System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
} catch (Exception e) {
rollback(connection);
e.printStackTrace();
} finally {
close(connection);
long endTime = System.currentTimeMillis();
System.out.println("wall time: " + (endTime - begTime) + " ms");
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0)) {
return DriverManager.getConnection(url);
} else {
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void rollback(Connection connection) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException {
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try {
if (rs != null) {
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i) {
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
} finally {
close(rs);
}
return results;
}
public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException {
List<Map<String, Object>> results = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters) {
ps.setObject(++i, parameter);
}
rs = ps.executeQuery();
results = map(rs);
} finally {
close(rs);
close(ps);
}
return results;
}
public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException {
int numRowsUpdated = 0;
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters) {
ps.setObject(++i, parameter);
}
numRowsUpdated = ps.executeUpdate();
} finally {
close(ps);
}
return numRowsUpdated;
}
}
You can write helper functions that parse a ResultSet and convert it into an ArrayList or an array or even the fields of an object. For instance, lets say you have a table of orders and then a query returns all of the rows of that table for a particular user (customer). We could then do something like this:
static List<Order> parseOrder(ResultSet rs) {
ArrayList<Order> orderList = new ArrayList<>();
while(rs.next() ) {
Order order = new Order();
order.setID(rs.getInt(1));
order.setCustomerID(rs.getInt(2));
order.setItemName(rs.getString(3));
orderList.add(order);
}
return orderList;
}
Simply turning the result set into an array of an array of Objects would be more general, but probably less useful.
I would leave it up to the calling function to close this ResultSet and possible the PreparedStatement (or Statement) and database connection.

can we create a common database class in java

i want to know if we can create a common database class same like we create a connection class and just call getConnection when we need connection to be established.
Basically, i want a database manager class which can handle database operation irrespective of tablename, columncount,etc.
tablename, columnname, values to be inserted would be passed as parameters from servlet.
that way, i can reduce duplication of code. m tryin to make a simple mvc application using jsp-servlets. my database is mysql. i dont know struts, spring, hibernate.
For Example, servlet code will call(databaseManager is the class name.) :
int count=databaseManager.getCount("tableName", "columnName", "value");
and in databaseManager, there will be a function -
public static int getCount(String tableName, String[] arrC, objectArray[] arrV)
{}
similarly, for other functions.
i googled and found out that it could be done using metadata.
but i dont know how to use it.
it would be helpful if u could post code of one function for similar approach.
Check DbUtils component of Apache Commons. Also there are examples provided.
Yes, sure you can. I have done something similar (but not the same) and there can be many approaches. I think you should google more, I'm sure, that there are lot of open source applications for database management/database clients. Try to get inspiration there.
Okay, here is some code for inspiration. It is not totally generic, or what are you looking for, but I think, this could lead you somewhere. If not, throw the stone. :-)
Database provider class:
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaProperty;
public class DatabaseProvider<T extends DatabaseObject> {
private static DatabaseProvider databaseProvider;
private static String connectionString = "";
private static String password = "";
private static String username = "";
private static boolean initialized = true;
public DatabaseProvider(){ }
public static void initDatabaseProvider() {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
}
catch(SQLException e){
initialized = false;
e.printStackTrace();
}
connectionString = "XXX";
username = "XXX";
password = "XXX";
}
public List<T> performSimpleSelectQuery(String table, String columns, String where, Class targetObj) throws SQLException {
if(!initialized) return null;
List<T> results = new ArrayList<T>();
Constructor ct;
DatabaseObject dbo;
try {
ct = targetObj.getConstructor(null);
dbo = (DatabaseObject)ct.newInstance(null);
}
catch(Exception e){
e.printStackTrace();
return null;
}
String[] cols = columns.split(",");
String[] properties = new String[cols.length];
for(int i = 0; i < cols.length; i++){
cols[i] = cols[i].trim();
properties[i] = dbo.getMappingFromColumnName(cols[i]);
}
Connection conn = DriverManager.getConnection(connectionString, username, password);
PreparedStatement pst = conn.prepareStatement("SELECT " + columns + " FROM " + table + (where.equals("") ? "" : " WHERE " + where));
pst.execute();
ResultSet rs = pst.getResultSet();
while(rs.next()){
try {
dbo = (DatabaseObject)ct.newInstance(null);
for(int i = 0; i < cols.length; i++){
BeanUtils.setProperty(dbo, properties[i], rs.getObject(cols[i]));
}
results.add((T)dbo);
}
catch(Exception e){
e.printStackTrace();
rs.close();
pst.close();
conn.close();
return null;
}
}
rs.close();
pst.close();
conn.close();
return results;
}
public int performInsert(String columns, String values, String table) throws SQLException {
String sqlInsert = "INSERT INTO " + table + " (" + columns + ") VALUES (" + values + ")";
Connection conn = DriverManager.getConnection(connectionString, username, password);
PreparedStatement pst = conn.prepareStatement(sqlInsert);
int toReturn = 0;
try {
toReturn = pst.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
pst.close();
conn.close();
return toReturn;
}
pst.close();
conn.close();
return toReturn;
}
}
Database object class:
import java.util.HashMap;
public abstract class DatabaseObject {
protected HashMap<String, String> dbToBeanMapping = new HashMap<String, String>();
public DatabaseObject() {
initialize();
}
protected abstract void initialize();
public String getMappingFromColumnName(String columnName) {
return dbToBeanMapping.get(columnName);
}
}
Example class:
public class CounterParty extends DatabaseObject {
private String name;
private int instrument;
private int partyId;
public int getPartyId() {
return partyId;
}
public void setPartyId(int partyId) {
this.partyId = partyId;
}
public CounterParty(){}
public int getInstrument() {
return instrument;
}
public void setInstrument(int instrument) {
this.instrument = instrument;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected void initialize() {
this.dbToBeanMapping.put("company_name", "name");
this.dbToBeanMapping.put("party_id", "partyId");
this.dbToBeanMapping.put("inst_id", "instrument");
}
}

Categories