我正在使用Spring 4和Hibernate 4但查询总是返回空列表,即使应该有几行。
这是模型
@DynamicUpdate
@Table(appliesTo = "comments")
public class Comment {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "content")
private String content;
... and some getters and setters ...
这是Spring配置部分
<beans:bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://mydbroot/circle" />
<beans:property name="username" value="user" />
<beans:property name="password" value="password" />
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
</beans:bean>
<tx:annotation-driven />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
<beans:bean id="commentDao"
class="com.hersbitcloud.cancercloud.models.circle.CommentDAO">
<beans:constructor-arg>
<beans:ref bean="sessionFactory" />
</beans:constructor-arg>
</beans:bean>
hibernate.cfg.xml文件
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
</session-factory>
对于DAO
public class CommentDAO {
private SessionFactory sessionFactory;
public CommentDAO(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
@Transactional
public List<Comment> GetComments() {
@SuppressWarnings("unchecked")
List<Comment> listComment = (List<Comment>) sessionFactory.getCurrentSession()
.createCriteria(Comment.class).list();
return listComment;
}
}
在我的控制器中
@Autowired
private CommentDAO commentDao;
@RequestMapping(value = "/comment", method = RequestMethod.GET) //, produces="application/json")
public int comment() {
List<Comment> listComments = commentDao.GetComments();
return listComments.size();
}
始终显示listComments.size()
为0。
有什么问题?
答案 0 :(得分:0)
尝试在您的班级CommentDAO
中添加以下这些内容,以便更改此内容:
private SessionFactory sessionFactory;
要:
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
答案 1 :(得分:0)
我认为@Transactional
用于对DB执行修改过程。删除@Transactional
并尝试一下,
public List<Comment> GetComments() {
@SuppressWarnings("unchecked")
List<Comment> listComment = (List<Comment>) sessionFactory.getCurrentSession()
.createCriteria(Comment.class).list();
return listComment;
}
将@Transactional
放在课堂上方。
如果您想执行动作db,请提供@Transactional(readOnly=false)
答案 2 :(得分:0)
@RaphaelRoth感谢您的回复。我通过改变
让一切顺利@DynamicUpdate
@Table(appliesTo = "comments")
进入
@Entity
@Table(name="comments")
它们都属于'javax.persistence。*'。