Execute sql in java

0

I have the following code:

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

My class:

public class DataBaseServiceImpl implements IDataBaseService {

  @Autowired
  private IDataBaseDao databaseDao;

  @Override
  @Transactional(readOnly = true)
  public List<Jdbc> findAll() {
    return databaseDao.findAll();
  }

and my other class

@Repository
public class DataBaseDao implements IDataBaseDao {

@Autowired
private HibernateTemplate hibernateTemplate;

@SuppressWarnings("unchecked")
@Override
public List<Jdbc> findAll() {
    return (List<Jdbc>) hibernateTemplate.find("from Jdbc");
}

This works without problems, but I want to execute a sql, now I have this:

@Override
public List<Column> getColumns(Jdbc jdbc, String tableName) throws SQLException {
    List<Column> result = new ArrayList<Column>();
    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;
    String query = null;

    try {
        connection = getConnection(jdbc);
        stmt = connection.createStatement();

            query = "Select column_name AS field,data_type as type from user_tab_columns where table_name= '" + tableName + "'";

        rs = stmt.executeQuery(query);

        while (rs.next()) {
            result.add(new Column(rs.getString("field"), rs.getString("type")));
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeConnection(rs, stmt, connection);
    }

    return result;
}

How can I also execute this query without opening a connection because I already injected it into the class DataBaseServiceImpl .

    
asked by sirdaiz 16.06.2017 в 09:40
source

1 answer

1

As you have hibernate configured and the handling of sessions does Spring

Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createSQLQuery(
                    "Select column_name AS field,data_type as type from user_tab_columns where table_name = ? ")
                               .setString(0, tableName);
query.setResultTransformer(new AliasToEntityOrderedMapResultTransformer());
List<Map<String, Object>> resultId = query.list();

Ideally, you will generate a DTO and map your resultSet to the DTO, but the List will still serve you. In the List you will return the list with one element per record where each element is a Map that contains the relation of the name of the column as key and the value as the value of the column

    
answered by 21.06.2017 в 01:27