I have a mysql table like this:
CREATE TABLE `sezione_menu` (
`id_sezione_menu` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nome` varchar(256) NOT NULL DEFAULT '',
`ordine` int(11) DEFAULT NULL,
PRIMARY KEY (`id_sezione_menu`)
)ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
I use apache dbutils to query my database, with these methods:
public static List<SezioneMenu> getSezioniMenu() {
String sql = "SELECT * FROM sezione_menu";
try {
QueryRunner qr = new QueryRunner(createDataSource());
ResultSetHandler rsh = new BeanListHandler(SezioneMenu.class);
List<SezioneMenu> sezioni = (List<SezioneMenu>)qr.query(sql, rsh);
return sezioni;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static DataSource createDataSource() {
BasicDataSource d = new BasicDataSource();
d.setDriverClassName(DRIVER);
d.setUsername(USERNAME);
d.setPassword(PASSWORD);
d.setUrl(DB_URL);
return d;
}
Now, if i run my application, it doesn't throw exception, but some fields (not all!) of my java bean SezioneMenu are empty (integer field equals zero and string field equals empty string).
This happen also with other tables and beans.
I used this method in the past in another system configuration without problems.
You can fix it in two ways:
As per dbutils doc,
Alias the column names in the SQL so they match the Java names: select social_sec# as socialSecurityNumber from person
Subclass BeanProcessor and override the mapColumnsToProperties() method to strip out the offending characters.
If you are keeping a class like this
public class SezioneMenuBean implements Serializable {
private int idSezioneMenu;
private String nome;
private int ordine;
public SezioneMenuBean() {
}
// Getters and setters for bean values
}
As per first solution write your queries something like this SELECT id_sezione_menu AS idSezioneMenu, name, ordine FROM sezione_menu.
Or
Based on second solution you can use GenerousBeanProcessor which is a subclass of BeanProcessor it ignores underscore & case sensitivity from column name. You don't have to implement your own custom BeanProcessor
GenerousBeanProcessor is available since version 1.6 of commons-dbutils.
Usage:
// TODO initialize
QueryRunner queryRunner = null;
ResultSetHandler<List<SezioneMenuBean>> resultSetHandler =
new BeanListHandler<SezioneMenuBean>(SezioneMenuBean.class, new BasicRowProcessor(new GenerousBeanProcessor()));
// best practice is specifying only required columns in the query
// SELECT id_sezione_menu, name, ordine FROM sezione_menu
final List<SezioneMenuBean> sezioneMenuBeans = queryRunner.query("SELECT * FROM sezione_menu", resultSetHandler);
for (SezioneMenuBean sezioneMenuBean : sezioneMenuBeans) {
System.out.println(sezioneMenuBean.getIdSezioneMenu());
}
I faced the same issue of BeanHandler/BeanHandlerList returning null or 0 for database columns.
As mentioned by #aelfric5578 in the comment, I have updated the Bean class with same names as Database, DBUtils returned values correctly.
Having BeanClass defined like this will solve your problem.
public class SezioneMenuBean{
int id_sezione_menu;
String nome;
int ordine;
public SezioneMenuBean(){
}
// Getters and setters for bean values
}
Related
I'm making a game for practice.
I have a spring boot/Maven project connected to a MySQL database. I was able to setup an api that simply retrieves everything from my "allriddles" table. It worked before, but now the api returns a json where some values are null for some keys. The only thing i was playing with was the application.properties on the spring boot file. I was hopping between "update" and "none" for the spring.jpa.hibernate.ddl-auto.
What could I have done wrong?
application.properties
spring.jpa.hibernate.format_sql=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/riddlesgame
spring.datasource.username=root
spring.datasource.password=RiddlesGame886
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.data.rest.base-path=/api/v1
server.port=8088
this is the database table and expected columns
this is the returned json with erronous null values
here is the model
#Entity
#Table(name = "allriddles")
public class Riddle {
/*
* ATTRIBUTES
*/
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String title;
private int difficulty;
private String prize;
private String riddlerName;
private int levels;
private String riddleDescription;
/*
* CONSTRUCTORS
*/
public Riddle() {}
public Riddle( String title, int difficulty, String prize, String riddlerName, int levels,
String description) {
super();
this.title = title;
this.difficulty = difficulty;
this.prize = prize;
this.riddlerName = riddlerName;
this.levels = levels;
this.riddleDescription = description;
}
}
this is my controller that calls a service
#RestController
public class GetRiddles {
#Autowired
RiddlesService rs;
#RequestMapping("/Riddles")
public List<Riddle> getAllRiddles(){
return rs.getAllRiddles();
}
the service that calls crud
#Service
public class RiddlesService {
#Autowired
RiddlesRepository riddlesRepository;
public List<Riddle> getAllRiddles(){
List<Riddle> riddles = new ArrayList<>();
riddlesRepository.findAll()
.forEach(riddles::add);
return riddles;
}
the crud interface
public interface RiddlesRepository extends CrudRepository<Riddle, Integer> {
}
and finally the console output if thats of any help
I tried the same thing, and got a similar result. It occurred, as you said, upon modifying spring.jpa.hibernate.ddl-auto to update. It ended up adding 2 new columns.
Hibernate: alter table allriddles add column riddle_description varchar(255)
Hibernate: alter table allriddles add column riddler_name varchar(255)
The original column names were riddleDescription and riddlerName and those remained with existing values. But the new columns will not have data in them. So assuming I recreated the same issue you had, either you have to
in the database: move data from old columns (without the underscore) to new columns (with the underscore) and remove old columns. Or
in the database: remove new columns (with the underscore). in Riddle.java change properties riddlerName and riddleDescription to riddlername and riddledescription.
I assume possibly you might have also changed at some point between all lower case and camelcase for those property names. Because camelcase properties will map to database as underscores (e.g. code - riddleName -> db column - riddle_name), while all lowercase will not have underscores (e.g. code - riddlername -> db column - riddlerName or riddlername).
This is the default way in which hibernate names columns in the table based on the fields defined in the entity.
To override the default behaviour you can use
#Column(name = "riddleName")
private String riddlerName;
#Column(name = "riddleDescription")
private String riddleDescription;
I am Using SqlServer 2012 and my Entity is
public class Something {
private Date rq;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "rq")
#Formula("CONVERT(DATE,rq)")
public Date getRq() {
return Rq;
}
public void setRq(Date rq) {
this.Rq = rq;
}
}
Hibernate debug log :
Hibernate:
select
CONVERT(dnypowergr0_.DATE,
dnypowergr0_.rq) as formula0_
from
db.dbo.something dnypowergr0_
I want to get the result of 'rq' that can truly 'convert' but as the log shows, the first argument of 'convert' was added an alias of the table, So this sql is error.
Have I written wrong code or used part of '#Formula' ?
Not sure how to make hibernate to do not insert table alias where it is not needed. But there is a workaround.
You can define a transient attribute (something like convertedRq) and convert value in Java. In this case rq will contain pure value of rq field, convertedRq will be calculated on fly.
Update: solution was posted here Hibernate #formula is not supportinng Cast() as int for teradata database :
public class Oracle10gDialectExtended extends Oracle10gDialect {
public Oracle10gDialectExtended() {
super();
/* types for cast: */
registerKeyword("int");
// add more reserved words as you need
}
}
(c) Sergio M C Figueiredo
I have a database column that needs to be encrypted, when passed from a hibernate backed webapp. The webapp is on tomcat 6, Hibernate 4, and Mysql as the backing store.
The problem however is that the password to encrypt/decrypt this field will only be available at runtime of the program. Initially I had hoped to use the AES_ENCRYPT/DECRYPT methods, outlined quite well here:
DataBase encryption in Hibernate
and here:
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-column-read-and-write
(Though this does refer to version 3.6 of hibernate, I believe it should be the same in 4.0).
However, since this uses the following notation:
#Column(columnDefinition= "LONGBLOB", name="encryptedBody")
#ColumnTransformer(
read="AES_DECRYPT(encryptedBody, 'password')",
write="AES_ENCRYPT(?, 'password')")
public byte[] getEncryptedBody() {
return encryptedBody;
}
public void setEncryptedBody(byte[] encryptedBody) {
this.encryptedBody = encryptedBody;
}
This requires that the password be specified in the annotation itself, and cannot be a variable.
Is there a way to use the database methods through hibernate in this manner, but with the password as a variable? Is there a better approach?
Currently there is not a way to parameterize the pieces of the read/write fragments. They are more meant as general purpose solutions. We have discussed adding support for #Encrypted in Hibernate that would roughly act like you suggest. #Encrypted would give more flexibility, like in-vm crypto versus in-db crypto, parameterization, etc.
JPA 2.1 also has a feature you could use, called attribute converters. They would only be able to apply in-vm crypto however.
You can Use Hibernate #Type attribute,Based on your requirement you can customize the annotation and apply on top of the fied. like :
public class PhoneNumberType implements UserType {
#Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
}
#Override
public Class returnedClass() {
return PhoneNumber.class;
}
// other methods
}
First, the null SafeGet method:
#Override
public Object nullSafeGet(ResultSet rs, String[] names,
SharedSessionContractImplementor session, Object owner) throws HibernateException,
SQLException {
int countryCode = rs.getInt(names[0]);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
return employeeNumber;
}
Next, the null SafeSet method:
#Override
public void nullSafeSet(PreparedStatement st, Object value,
int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
}
}
Finally, we can declare our custom PhoneNumberType in our OfficeEmployee entity class:
#Entity
#Table(name = "OfficeEmployee")
public class OfficeEmployee {
#Columns(columns = { #Column(name = "country_code"),
#Column(name = "city_code"), #Column(name = "number") })
#Type(type = "com.baeldung.hibernate.customtypes.PhoneNumberType")
private PhoneNumber employeeNumber;
// other fields and methods
}
This might solve your problem, This will work for all database. if you want more info refer :: https://www.baeldung.com/hibernate-custom-types
similarly you have to do UTF-8 encoding/Decoding and ISO-8859-1 Decoding/encoding
Let's say I have to fire a query like this:
Select primarykey, columnname, old_value, new_value from first_audit_log;
Select primarykey, columnname, old_value, new_value from second_audit_log;
Select primarykey, columnname, old_value, new_value from third_audit_log; ...so on
audit_log is not mapped as JPA enity to any class and I strictly can't create n number of classes for n number of *_audit_logs.
Using native query feature, how best I can map this to a generic class? Trying to SELECT NEW feature, but not sure... Hence any help is appreciated.
Since your audit logs tables share the same columns, you can create a view that "unifies" those tables and map a single Java class to that view. I believe you can, since you don't need to write updates, I guess.
As an alternative, using native queries would be a good choice.
EDIT:
1) If your audit logs are already views, you can create a view based on other views, if you don't want to create a mapping Java class for each of them. Just remember to add a dummy column that has value 1 if the row comes from the "first" audit log, 2 if it comes from the second, and so on, so you can set them apart.
2) In order to use native queries, assuming your persistence provider is Hibernate, you can do like in this example:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
Session sess = em.unwrap(Session.class); // <-- Use Hibernate-specific features
SQLQuery query = sess.createSQLQuery(
"SELECT AVG(age) AS averageAge, AVG(salary) as averageSalary FROM persons");
query.setResultTransformer(Transformers.aliasToBean(MyResult.class));
MyResult result = (MyResult) query.list().get(0);
where MyResult is declared as follows:
public class MyResult {
private BigDecimal averageAge;
private BigDecimal averageSalary;
public BigDecimal getAverageAge() {
return averageAge;
}
public void setAverageAge(BigDecimal averageAge) {
this.averageAge = averageAge;
}
public BigDecimal getAverageSalary() {
return averageSalary;
}
public void setAverageSalary(BigDecimal averageSalary) {
this.averageSalary = averageSalary;
}
}
and the persons table is like this (MySQL syntax):
CREATE TABLE `persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`salary` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
You can easily adapt this example to your needs, just replace persons and MyResult with what you want.
The aliases in the sql query is automatically converted to upper case and its looking for the setter in Upper case as a result org.hibernate.PropertyNotFoundException Exception is thrown. Any suggestions would be greatly appreciated.
For instance, the below statement is looking for the setter ID instead of Id/id (Could not find setter for ID on class Data)
List<Data> result = entityManager.unwrap(Session.class)
.createSQLQuery("Select id as id from table")
.setParameter("day", date.getDayOfMonth())
.setParameter("month", date.getMonthOfYear())
.setParameter("year", date.getYear())
.setResultTransformer(Transformers.aliasToBean(Data.class))
.list();
class Data {
Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
I am trying to implement MyBatis in my project at work. It is a legacy system, which uses vanilla JDBC to access the database, solely through stored procedures. I understand that to call a stored procedure, MyBatis requires an object which contains the input parameters for the stored procedure and another that will hold the result set. Not sure if this is entirely true.
To prevent creating too many data entities in the system, I want to reuse the existing ones. And here is where the problem arises. Let me explain what the typical situation/scenario I am facing, and then how I am trying to solve it.
Let's say I have the following data entity(ies) in the system:
class Account {
private int accountID;
private String accountName;
private OrganizationAddress address;
// Getters-Setters Go Here
}
class OrganizationAddress extends Address {
// ... some attributes here
// Getters-Setters Go Here
}
class Address {
private String address;
private String city;
private String state;
private String country;
// Getters-Setters Go Here
}
I am using annotations, so my Mapper class has something like this:
#Select(value = "{call Get_AccountList(#{accountType, mode=IN, jdbcType=String})}")
#Options(statementType = StatementType.CALLABLE)
#Results(value = {
#org.apache.ibatis.annotations.Result
(property = "accountID", column = "Account_ID"),
#org.apache.ibatis.annotations.Result
(property = "accountName", column = "Organization_Name"),
#org.apache.ibatis.annotations.Result
(property = "state", column = "State", javaType=OrganizationAddress.class)
})
List<Account> getAccountList(Param param);
Problem: When I make the call to the stored procedure, the Account object has the state always null.
To add to the injury, I do not have access to the source of the above data entities. So I couldn't try the solution provided on this link either - Mybatis select with nested objects
My query:
Is it possible for me to use the data entites already present in the system, or do I have to create new ones, and then map the data to the existing ones?
If yes, how do I go about it? Any references, if any.
If no, is there a way to reduce the number of data entities I would create to call the stored procedures (for both in and out parameters)?
I think the best solution for your situation (if I understand it correctly) is to use a MyBatis TypeHandler that will map the state column to an OrganizationAddress object.
I've put together a example based on the information you provided and it works. Here is the revised annotated Mapper:
// Note: you have an error in the #Select line => maps to VARCHAR not "String"
#Select(value = "{call Get_AccountList(#{accountType, mode=IN, jdbcType=VARCHAR})}")
#Options(statementType = StatementType.CALLABLE)
#Results(value = {
#org.apache.ibatis.annotations.Result
(property = "accountID", column = "Account_ID"),
#org.apache.ibatis.annotations.Result
(property = "accountName", column = "Organization_Name"),
#org.apache.ibatis.annotations.Result
(property = "address", column = "State", typeHandler=OrgAddressTypeHandler.class)
})
List<Account> getAccountList(Param param);
You need to map the address field of Account to the "state" column and use a TypeHandler to create an OrganizationAddress with its "state" property filled in.
The OrgAddressTypeHandler I created looks like this:
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
public class OrgAddressTypeHandler extends BaseTypeHandler<OrganizationAddress> {
#Override
public OrganizationAddress getNullableResult(ResultSet rs, String colName) throws SQLException {
OrganizationAddress oa = new OrganizationAddress();
oa.setState(rs.getString(colName));
return oa;
}
#Override
public OrganizationAddress getNullableResult(ResultSet rs, int colNum) throws SQLException {
OrganizationAddress oa = new OrganizationAddress();
oa.setState(rs.getString(colNum));
return oa;
}
#Override
public OrganizationAddress getNullableResult(CallableStatement cs, int colNum) throws SQLException {
OrganizationAddress oa = new OrganizationAddress();
oa.setState(cs.getString(colNum));
return oa;
}
#Override
public void setNonNullParameter(PreparedStatement arg0, int arg1, OrganizationAddress arg2, JdbcType arg3) throws SQLException {
// not needed for this example
}
}
If you need a more complete working example than this, I'll be happy to send more of it. Or if I have misunderstood your example, let me know.
With this solution you can use your domain objects without modification. You just need the TypeHandler to do the mapping and you don't need an XML mapper file.
Also I did this with MyBatis-3.1.1 in MySQL. Here is the simple schema and stored proc I created to test it:
DROP TABLE IF EXISTS account;
DROP TABLE IF EXISTS organization_address;
CREATE TABLE account (
account_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
organization_name VARCHAR(45) NOT NULL,
account_type VARCHAR(10) NOT NULL,
organization_address_id SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (account_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE organization_address (
organization_address_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
address VARCHAR(45) NOT NULL,
city VARCHAR(45) NOT NULL,
state VARCHAR(45) NOT NULL,
country VARCHAR(45) NOT NULL,
PRIMARY KEY (organization_address_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO organization_address VALUES(1, '123 Foo St.', 'Foo City', 'Texas', 'USA');
INSERT INTO organization_address VALUES(2, '456 Bar St.', 'Bar City', 'Arizona', 'USA');
INSERT INTO organization_address VALUES(3, '789 Quux Ave.', 'Quux City', 'New Mexico', 'USA');
INSERT INTO account VALUES(1, 'Foo', 'Type1', 1);
INSERT INTO account VALUES(2, 'Bar', 'Type1', 2);
INSERT INTO account VALUES(3, 'Quux', 'Type2', 3);
DROP PROCEDURE IF EXISTS Get_AccountList;
DELIMITER $$
CREATE PROCEDURE Get_AccountList(IN p_account_type VARCHAR(10))
READS SQL DATA
BEGIN
SELECT a.account_id, a.organization_name, o.state
FROM account a
JOIN organization_address o ON a.organization_address_id = o.organization_address_id
WHERE account_type = p_account_type
ORDER BY a.account_id;
END $$
DELIMITER ;