要求是从数据库中获取记录,其中在运行时选择了特定列和表名。
我正在使用Java,Hibernate和Mysql。可以使用JDBC。但我想用hibernate来做。
发布提示,如果有人知道
提前致谢
答案 0 :(得分:0)
Hibernate
的功能多于JDBC
。最好的选择是Hibernate
支持Object Oriented Principles
。您可以对您的实体使用Polymorphism
,Inheritance
,Encapsulation
。
您必须拥有BaseEntity
类,并且所有其他类必须从此类扩展。
public class BaseEntity {
}
然后所有其他类都扩展了这个类。假设您有另外两个类或实体。
User.class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "USERS")
@Entity
public class User extends BaseEntity implements Serializable {
@Id
@Column(name = "ID")
private int id;
@Column(name = "NAME")
private String name;
@Column(name = "SURNAME")
private String surname;
public User() {
}
public User(int id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
Info.class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "INFO")
@Entity
public class Info extends BaseEntity implements Serializable {
@Column(name = "TEXT")
private String text;
@Id
@Column(name = "ID")
private int id;
public Info() {
}
public Info(String text, int id) {
this.text = text;
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
另外,您必须为mapping
每个类添加configuration.hbm.xml
标记
您的DAO
如下所示。
public List getList(BaseEntity baseEntity, String[] columnNames) {
Criteria criteria = session.createCriteria(baseEntity.getClass(), "be");
ProjectionList projectionList = Projections.projectionList();
for (String columnName : columnNames) {
projectionList.add(Projections.property("be." + columnName), columnName); // adding column for selection
}
criteria.setProjection(projectionList);
criteria.setResultTransformer(new AliasToBeanResultTransformer(baseEntity.getClass())); // for mapping result to entity
return criteria.list();
}
public static void main(String[] args) {
String[] columnNames = {"name", "surname"}; // columnNames which you want to select
List<Info> users = new GeneralDAO().getList(new User(), columnNames); // you can pass any class User, Info or etc.
}
答案 1 :(得分:0)
好吧,Hibernate可以做的不仅仅是JDBC,你正在寻找的东西可以用Hibernate这样编写:
Query query = session.createSQLQuery(
"select s.stock_code from stock s where s.stock_code = :stockCode")
.setParameter("stockCode", "7277");
List result = query.list();
正如您所看到的,表名和列可以动态定义,这至少与JDBC相同,甚至可能更简单。您不必使用参数,显然可以在代码中模块化地构建查询。
参考更多细节 https://www.mkyong.com/hibernate/hibernate-native-sql-queries-examples/