stp
stp

Reputation: 147

How to assign a column name of Spring Model from a variable

I have a Sring hibernate Model as follows

@Entity
@Table(name = "client")
public class Category {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private long id;

private String type;
...
...
...

I have some 50 columns. Now while inseting a new row into this table, how can i give the column name dynamically,

Client client = new Client();
String columnName = "type";

How do I update client model with the column name given in string columnName?

Upvotes: 1

Views: 1993

Answers (2)

Raju Rudru
Raju Rudru

Reputation: 1132

If you want to set the values for columns dynamically, you can use Java reflection concept. Have a look at the Java reflection concept, following links may be helpful

http://tutorials.jenkov.com/java-reflection/fields.html

http://www.avajava.com/tutorials/lessons/how-do-i-get-and-set-a-field-using-reflection.html

Upvotes: 1

Rohith K
Rohith K

Reputation: 1492

For updating the table, we need to get the the field from the category Object and set the new value for that and finally invoke the save() method. But if you want to set the field values dynamically, then you need to find the the attributes present inside the Category object using Java reflection methods. Use methods provided by Field object in java and use them. Then after getting the filed invoke the set method of the same and update the value. Category.class.getDeclaredFields().

Upvotes: 0

Related Questions