Hibernate本机sql查询无法正常工作

时间:2016-04-18 10:42:47

标签: java mysql sql hibernate

 public ChatRoomUserHelper isUserSubscribe(){
    Transaction transaction = null;
    ChatRoomUserHelper userHelper = null;
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        transaction = session.beginTransaction();
        userHelper = (ChatRoomUserHelper) session.createSQLQuery("SELECT * FROM CHATROOM_USERHELPER WHERE CHAT_ROOMNAME ='chatdlya3uuid' AND USER_NICKNAME ='nikita555' and STATUS = 'subscribe'").
                addEntity(ChatRoomUserHelper.class);
        session.getTransaction().commit();
    }catch (RuntimeException e){
        if(transaction!=null){
            transaction.rollback();
        }
        e.printStackTrace();
    }
    return userHelper;
}

这是我的方法,它返回硬编码的ChatRoomUserHelper对象。 这是我的项目POJO类ChatRoomUserHelper。

 @Entity
 @Table(name = "CHATROOM_USERHELPER")
 @Embeddable
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.FIELD)
 public class ChatRoomUserHelper {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int id;
@Column(name = "CHAT_ROOMNAME")
private String chatRoomName;
@Column(name = "USER_NICKNAME")
private String userNickName;
@Column(name = "STATUS")
private String userStatus;

public ChatRoomUserHelper(String chatRoomName,String userNickName){
    this.chatRoomName = chatRoomName;
    this.userNickName = userNickName;
    this.userStatus = "subscribe";
}

public ChatRoomUserHelper(){}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getChatRoomName() {
    return chatRoomName;
}

public void setChatRoomName(String chatRoomId) {
    this.chatRoomName = chatRoomId;
}

public String getUserNickName() {
    return userNickName;
}

public void setUserNickName(String userNickName) {
    this.userNickName = userNickName;
}

public String getUserStatus() {
    return userStatus;
}

public void setUserStatus(String userStatus) {
    this.userStatus = userStatus;
}

}         My Table with rows 当我在IntellijIdea和MySQL工作台中执行此方法时,它可以正常工作。

MySQL Workbench

但是当我在程序中使用这种方法时,它并不想按照我想要的方式工作并回滚

我知道这个问题不是在初始化Session Factory等等,因为所有其他东西都运行正常。此查询中存在问题,但我不知道如何解决此问题

   2016-04-18 13:24:52 DEBUG TransactionImpl:51 - begin
   2016-04-18 13:24:52 DEBUG TransactionImpl:86 - rolling back
   2016-04-18 13:25:14 DEBUG DriverManagerConnectionProviderImpl:49 -     Connection pool now considered primed; min-size will be maintained

我得到的所有日志

1 个答案:

答案 0 :(得分:0)

您可能想尝试这一行:

userHelper = (ChatRoomUserHelper) session.createSQLQuery("SELECT * FROM CHATROOM_USERHELPER c WHERE c.CHAT_ROOMNAME ='chatdlya3uuid' AND c.USER_NICKNAME ='nikita555' and c.STATUS = 'subscribe'").addEntity("c", ChatRoomUserHelper.class);

希望这有帮助!