Java Hibernate运行问题

错误信息

 java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.jboss.logging.Logger$1.run(Logger.java:2554)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2516)
    at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:28)
    at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:24)
    at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:86)
    at com.lee.hibernate.HibernateTest.test(HibernateTest.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: javax.transaction.SystemException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 33 more

hibernate.cfg.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <!-- 数据库的基本信息 -->
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>

        <!-- Hibernate基本信息 -->
        <!-- Hibernate设置数据库方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

        <!-- 是否在控制台显示SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 格式化SQL语句 -->
        <property name="format_sql">true</property>
        <!-- 指定自动生成数据表策略 -->
        <property name="hibernate.hbm2ddl.auto">create</property>

        <!-- 关联.hbm.xml对象 -->
        <mapping resource="/com/lee/hibernate/News.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

News.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-11-27 21:27:39 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.lee.hibernate.News" table="NEWS">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="title" type="java.lang.String">
            <column name="TITLE" />
        </property>
        <property name="author" type="java.lang.String">
            <column name="AUTHOR" />
        </property>
        <property name="date" type="java.sql.Date">
            <column name="DATE" />
        </property>
    </class>
</hibernate-mapping>

News.java

 package com.lee.hibernate;

import java.sql.Date;

public class News {
    private Integer id;
    private String title;
    private String author;
    private Date date;

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public News() {
        super();
    }

    public News(String title, String author, Date date) {
        super();
        this.title = title;
        this.author = author;
        this.date = date;
    }

    @Override
    public String toString() {
        return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]";
    }

}

HibernateTest.java

 package com.lee.hibernate;

import java.sql.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
//import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
//import org.hibernate.service.ServiceRegistry;
import org.junit.Test;

public class HibernateTest {

    @Test
    public void test() {

        //1 创建一个SessionFactory对象
        SessionFactory sessionFactory = null;
        //1) 创建Configuration对象: 对应hibernate的基本配置信息和对象映射信息
        Configuration configuration = new Configuration().configure();

        sessionFactory = configuration.buildSessionFactory();

        //2)创建sessionRegistry对象: hibernate 4.x新添加的对象
        //hibernate的任何配置和服务都需要在该对象注册后才能有效.
//      ServiceRegistry serviceRegistry = 
//              new StandardServiceRegistryBuilder().
//                  applySettings(configuration.getProperties())
//                      .build();


        //3)
//      sessionFactory = configuration.buildSessionFactory(sessionRegistry);

        //2 创建一个Session对象
        Session session = sessionFactory.openSession();

        //3 开启事务
        Transaction transaction = session.beginTransaction();

        //4 执行保存操作
        News news = new News("Java", "Lee", new Date(new java.util.Date().getTime()));
        session.save(news);

        //5 提交事务
        transaction.commit();

        //6 关闭Session
        session.close();

        //7 关闭SessionFactory对象
        sessionFactory.close();
    }

}

hibernate框架是5.0.0.Final版本
mysql-jdbc驱动是5.1.37-bin版本
JUnit是4.10版本
Java8
Eclipse Version: Mars.1 Release (4.5.1)
Windows10

Configuration错误, 但不了解, 麻烦解答

3个回答

少了jta.jar包列 Hibernate会调用jta.jar的内容 加进去就OK了

Ro_bot
Ro_bot 采纳之后, 发现修改没了, 在hibernate库中添加jta.jar包后还有问题, 那就是找不到News的配置文件, 需要在hibernate.cfg.xml中的<mapping/>修改为<mapping resource="com/lee/hibernate/News.hbm.xml/>, 方言修改为MySQLDialect, 以上
4 年多之前 回复
Ro_bot
Ro_bot 回复JinJie_Zhang: 谢谢, 按照你的说法, 已解决
4 年多之前 回复
zjj7188
JinJie_Zhang java.lang.NoClassDefFoundError: javax/transaction/SystemException,这里显示事务处理出错,表示缺少了jta包
4 年多之前 回复

类没有找到,配置的问题,检查下

Ro_bot
Ro_bot 姐姐, 所有东西都找了, 全部写在上面了. 或者提示多一下~
4 年多之前 回复

配置的问题,,,你再看下代码

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java hibernate运行起动报错

严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1099) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1621) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:323) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:456) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:131) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84) at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:267) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1341) at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:814) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:732) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) ... 29 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.GeneratedConstructorAccessor9.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:107) ... 43 more Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for xtjy in class com.znyy.bean.lis.base.LisInstrument at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:306) at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:299) at org.hibernate.mapping.Property.getGetter(Property.java:294) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:300) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:141) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:78) ... 47 more

Hibernate或者 Java 怎样运行xxx.sql的脚本文件,,,

在公司的项目中看到有一些xxx.sql的脚本文件,而且在启动项目时看日志发现确实运行 了这些sql脚本文件,而且项目中有一些看不懂的类和方法,我在猜测这些类是否与 执行sql脚本文件相关,所以希望大侠帮助我解答下 Hibernate或者 Java 怎样运行xxx.sql的脚本文件,验证一下我的猜想,,

Hibernate 运行报错,空指针异常

INFO: HHH000401: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:orcl] 九月 15, 2018 11:39:14 上午 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000046: Connection properties: {user=scott, password=****} Exception in thread "main" java.lang.NullPointerException at java.lang.String.<init>(String.java:166) at oracle.sql.CharacterSet.AL32UTF8ToString(CharacterSet.java:1628) at oracle.jdbc.driver.DBConversion.CharBytesToString(DBConversion.java:834) at oracle.jdbc.driver.DBConversion.CharBytesToString(DBConversion.java:773) at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOauth(T4CTTIoauthenticate.java:816) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:376) at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:441) at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:839) at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:204) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117) at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156) at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785) at com.util.HibernateUtil.getSessionFactory(HibernateUtil.java:18) at com.test.Test1.get(Test1.java:61) at com.test.Test1.main(Test1.java:30) hibernate.cfg.xml是这样配置的. <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="connection.username">scott</property> <property name="connection.password">tiger</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="show_sql">true</property> <mapping resource="com/bean/User.hbm.xml"/> </session-factory> </hibernate-configuration> 我看其他同学正确的代码,我出的问题是在方言那里就执行不下去了. 哪位大侠可以帮我看一下是什么问题吗 是oracle的字符集安装不好然后导致这部分取不到值? 如果这样的话,要怎么处理呢.

为什么我的hibernate项目在java项目中能运行 web项目中运行不了

这是测试类的报错信息 Caused by: org.hibernate.HibernateException: Unable to get the default Bean Validation factory at org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:127) at org.hibernate.cfg.Configuration.applyBeanValidationConstraintsOnDDL(Configuration.java:1704) at org.hibernate.cfg.Configuration.applyConstraintsToDDL(Configuration.java:1654) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1445) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856) at common.HibernateUtil.<clinit>(HibernateUtil.java:13) ... 2 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:118) ... 7 more Caused by: org.hibernate.HibernateException: Unable to build the default ValidatorFactory at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:383) at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:109) ... 12 more Caused by: javax.validation.ValidationException: Unable to instantiate Configuration. at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:272) at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111) at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:380) ... 13 more Caused by: java.lang.NullPointerException at java.util.ResourceBundle.getBundle(ResourceBundle.java:1026) at org.hibernate.validator.engine.ResourceBundleMessageInterpolator.loadBundle(ResourceBundleMessageInterpolator.java:202) at org.hibernate.validator.engine.ResourceBundleMessageInterpolator.getFileBasedResourceBundle(ResourceBundleMessageInterpolator.java:182) at org.hibernate.validator.engine.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:81) at org.hibernate.validator.engine.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:73) at org.hibernate.validator.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:57) at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43) at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269) ... 15 more //分割符------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 这是在访问web时的报错!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! org.hibernate.exception.JDBCConnectionException: Cannot open connection Caused by: java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@localhost:1521:XE

hibernate 出错 java.lang.ClassCastException

[size=medium]刚刚学hibernate ,运行时出现异常 Exception in thread "main" java.lang.ClassCastException: java.lang.String at org.hibernate.type.ComponentType.toLoggableString(ComponentType.java:377) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:112) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate( 下面是代码: [code="java"] public class TestHibernate { Configuration cfg; SessionFactory sf; Session session; public static void main(String[] args){ TestHibernate test = new TestHibernate(); test.work(); } public void work(){ cfg = new Configuration().configure(); sf = cfg.buildSessionFactory(); session = sf.openSession(); User user = new User(); user.setUserID("22"); user.setPassword("d"); user.setUsername("c"); session.beginTransaction(); session.save(user); session.getTransaction().commit(); } } [/code] pojo的代码: [code="java"] public class User implements Serializable { private String userID; private String username; private String password; public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } [/code] [code="java"] <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="vo.User" table="myproject1_t_user" catalog="myproject1"> <composite-id name="userID" class="vo.User"> <key-property name="userID" type="java.lang.String"> <column name="user_id" /> </key-property> <key-property name="username" type="java.lang.String"> <column name="username" /> </key-property> <key-property name="password" type="java.lang.String"> <column name="password" /> </key-property> </composite-id> </class> </hibernate-mapping> [/code][/size]

hibernate运行总是出错 求解答

一直出错困扰我两天了 求大家帮忙解决一下 谢谢了 一月 18, 2016 11:10:26 下午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.0.7.Final} 一月 18, 2016 11:10:26 下午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 一月 18, 2016 11:10:26 下午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 一月 18, 2016 11:10:26 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time. 一月 18, 2016 11:10:26 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 一月 18, 2016 11:10:27 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) 一月 18, 2016 11:10:27 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/hibernate] 一月 18, 2016 11:10:27 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} 一月 18, 2016 11:10:27 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false 一月 18, 2016 11:10:27 下午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 1 (min=1) 一月 18, 2016 11:10:27 下午 org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect 一月 18, 2016 11:10:27 下午 org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 一月 18, 2016 11:10:28 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000227: Running hbm2ddl schema export 一月 18, 2016 11:10:28 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000230: Schema export complete org.hibernate.MappingException: Unknown entity: com.hi.Students at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:781) at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1520) at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192) at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177) at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73) at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:679) at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671) at org.hibernate.internal.SessionImpl.save(SessionImpl.java:666) at com.cat.StudentsTest.testSaveStudents(StudentsTest.java:41) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 一月 18, 2016 11:10:28 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost/hibernate] hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">mona</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.pool_size">1</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping resource="com/hi/Students.hbm.xml"/> </session-factory> </hibernate-configuration> Students.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hi"> <class name="com.hi.Students" table="STUDENTS"> <id name="id" type="int"> <column name="ID" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="age" type="int"> <column name="AGE" /> </property> </class> </hibernate-mapping> Student.java package com.hi; //学生类 public class Students { private int id; private String name; private int age; public Students() { } public Students(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Students [id=" + id + ", name=" + name + ", age=" + age + "]"; } } StudentsTest.java package com.cat; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.hi.Students; public class StudentsTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ Configuration config = new Configuration().configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); sessionFactory = config.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession(); transaction = session.beginTransaction(); } @After public void destory(){ transaction.commit(); session.close(); sessionFactory.close(); } @Test public void testSaveStudents(){ Students s = new Students(1, "张三丰", 15); session.save(s); } }

hibernate 在tomcat环境下运行的问题

新建了一个hibernate工程 在 main方法内运行正常实现查询。 将其在tomcat中启动后,hibernate抛出以下异常, java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration 请问是哪的问题吗。

hibernate5.2.4:每次运行hibernate都会创建表

我导入的jar包是required里所有和jdbc hibernate.cfg.xml 注意hbm2ddl.auto属性 ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.password">scott</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> <property name="hibernate.connection.username">scott</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="entity/Emp.hbm.xml"/> <mapping resource="entity/Dept.hbm.xml"/> </session-factory> </hibernate-configuration> ``` emp映射文件 ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="entity.Emp" table="EMP"> <id name="empno" type="java.lang.Integer"/> <property name="ename" type="java.lang.String"/> <property name="job" type="java.lang.String"/> <property name="mgr" type="java.lang.Integer"/> <property name="hiredate" type="java.sql.Date"/> <property name="sal" type="java.lang.Double"/> <property name="comm" type="java.lang.Double"/> <many-to-one class="entity.Dept" column="deptno" name="d"/> </class> </hibernate-mapping> ``` dept映射文件 ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="entity.Dept" table="DEPT"> <id name="deptno" type="java.lang.Integer"/> <property generated="never" lazy="false" name="dname" type="java.lang.String"/> <property generated="never" lazy="false" name="loc" type="java.lang.String"/> <list name="l" table="EMP"> <key column="deptno"/> <list-index column="deptNo"/> <one-to-many class="entity.Emp"/> </list> </class> </hibernate-mapping> ``` java测试类 ``` package test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import entity.Emp; public class Test { public static void main(String[] args) { StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Emp e = new Emp(); e.setEmpno(652); session.save(e); session.getTransaction().commit(); } } ``` 控制台信息 ``` 十一月 21, 2016 8:56:30 下午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.2.4.Final} 十一月 21, 2016 8:56:30 下午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 十一月 21, 2016 8:56:30 下午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 十一月 21, 2016 8:56:31 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 十一月 21, 2016 8:56:31 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time. 十一月 21, 2016 8:56:32 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time. 十一月 21, 2016 8:56:32 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) 十一月 21, 2016 8:56:32 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thava:191) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:193) at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:999) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315) at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1890) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1855) at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:304) at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ``` 如果我把hbm2ddl属性换成create也会造成这种冲突,请问大神怎么破

hibernate项目运行一段时间后,JDBC报错

type Exception report message JDBC commit failed description The server encountered an internal error that prevented it from fulfilling this request. exception org.hibernate.TransactionException: JDBC commit failed org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:161) filter.TestFilter.doFilter(TestFilter.java:34) root cause com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Communications link failure during commit(). Transaction resolution unknown. sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) java.lang.reflect.Constructor.newInstance(Constructor.java:526) com.mysql.jdbc.Util.handleNewInstance(Util.java:425) com.mysql.jdbc.Util.getInstance(Util.java:408) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886) com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) com.mysql.jdbc.ConnectionImpl.commit(ConnectionImpl.java:1559) org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170) org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146) filter.TestFilter.doFilter(TestFilter.java:34) 项目使用的是hibernate+struts2+Mysql;项目不是跑起来就报错,是运行一段时间后就报错。服务器重启就可以了,但一段时间后又报错。mysql驱动用3.0的时候也是这个情况,不过抱错是No operations allowed after connection closed;现在换成最新的5.o就报这个个错误。求高手解决。。。 事务我直接用了个过滤器 public class TestFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest requ, ServletResponse respo, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)requ; request.setCharacterEncoding("utf-8"); Session session=HibernateSessionFactory.getSession(); Transaction tr=session.beginTransaction(); chain.doFilter(request, respo); tr.commit();------报错在这行,34行 HibernateSessionFactory.closeSession(); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }

spring+hibernate游标不释放问题

系统使用spring+hibernate连接池与spring事务设置如下: [code="java"] <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@192.168.1.106:1521:orcl</value> </property> <property name="user"> <value>wjcx</value> </property> <property name="password"> <value>wjcx</value> </property> <!--连接池中保留的最小连接数。--> <property name="minPoolSize"> <value>5</value> </property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize"> <value>30</value> </property> <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize"> <value>10</value> </property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime"> <value>60</value> </property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement"> <value>5</value> </property> <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0--> <property name="maxStatements"> <value>0</value> </property> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>60</value> </property> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts"> <value>30</value> </property> <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false--> <property name="breakAfterAcquireFailure"> <value>true</value> </property> <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 等方法来提升连接测试的性能。Default: false --> <property name="testConnectionOnCheckout"> <value>false</value> </property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.cache.provider_class">com.jweb.common.cache.OSCacheProvider</prop> <prop key="hibernate.cache.use_query_cache">false</prop> </props> </property> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="baseTxProxy" abstract="true" lazy-init="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="edit*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="create*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> [/code] dao中的代码如下 [code="java"] public List getListByArticle(ArticleModel article, String orderby, int firstResult, int maxResults,String tid) { String hql = "from UserModel"; Session session = this.getSession(); Query query = session.createQuery(hql); query.setFirstResult(firstResult); query.setMaxResults(maxResults); return query.list(); } [/code] 里面有很多如上面的方法:但系统运行一段时间后总是游标超出最大值!因为用了spring事务,service类中没有关闭连接.但不知道为什么游标老是超出,希望有人解答! [b]问题补充:[/b] 程序有些地方使用了HibernateTemplate这个,但因为存在一些复杂SQL的组装只想知道上面这种写法会不会关掉游标的. [b]问题补充:[/b] 不是使用spring的事务管理就不用关连接吗 [b]问题补充:[/b] 发现添加了session.close();系统后就会报得不到session了!象上面这种写法有什么补求的办法吗?因为代码已经写了很多了!

hibernate+mysql问题

<p>UserModel.java</p> <p>package cn.javass.model;</p> <p>public class UserModel {<br> private Integer uuid;<br> private String name;<br> private Integer age;<br> public Integer getUuid() {<br>  return uuid;<br> }<br> public void setUuid(Integer uuid) {<br>  this.uuid = uuid;<br> }<br> public String getName() {<br>  return name;<br> }<br> public void setName(String name) {<br>  this.name = name;<br> }<br> public Integer getAge() {<br>  return age;<br> }<br> public void setAge(Integer age) {<br>  this.age = age;<br> }<br> <br>}</p> <p> </p> <p>UserModel.hbm.xml(我想配uuid自增)</p> <p>&lt;?xml version="1.0"?&gt;<br>&lt;!DOCTYPE hibernate-mapping PUBLIC <br> "-//Hibernate/Hibernate Mapping DTD 3.0//EN"<br> "<a href="http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd</a>"&gt;<br>&lt;hibernate-mapping <br> package="org.hibernate.auction"&gt;<br> &lt;class name="cn.javass.model.UserModel" table="tbl_user"&gt;<br>  &lt;id name="uuid" unsaved-value="0"&gt; <br>   &lt;generator class="increment"/&gt;<br>  &lt;/id&gt;<br>  &lt;property name="name"/&gt;<br>  &lt;property name="age"/&gt;<br> &lt;/class&gt;<br>  <br>&lt;/hibernate-mapping&gt;</p> <p> </p> <p>hibernate.cfg.xml</p> <p> </p> <p>&lt;?xml version='1.0' encoding='UTF-8'?&gt;<br>&lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "<a href="http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd</a>"&gt;</p> <p>&lt;hibernate-configuration&gt;</p> <p> &lt;session-factory&gt;<br>  <br>  &lt;property name="hibernate.connection.driver_class"&gt;org.gjt.mm.mysql.Driver&lt;/property&gt;<br>  &lt;property name="hibernate.connection.url"&gt;jdbc:mysql://localhost:3306/dhwebnms&lt;/property&gt;<br>  &lt;property name="hibernate.connection.username"&gt;root&lt;/property&gt;<br>  &lt;property name="hibernate.connection.password"&gt;xxxxxx&lt;/property&gt;<br>  <br>  &lt;property name="show_sql"&gt;true&lt;/property&gt;<br>  &lt;property name="dialect"&gt;net.sf.hibernate.dialect.MySQLDialect&lt;/property&gt;<br>  &lt;mapping resource="cn/javass/model/UserModel.hbm.xml"/&gt;  <br> &lt;/session-factory&gt;</p> <p>&lt;/hibernate-configuration&gt;</p> <p> </p> <p>public class UserDao {<br> public boolean  create(UserModel um,SessionFactory sf){<br>  Session se=null;<br>  Transaction tx=null;<br>  try{<br>   se=sf.openSession();<br>   tx=se.beginTransaction();<br>   se.save(um);<br>   tx.commit();<br>   se.close();<br>  }catch(Exception e){<br>   return false;<br>  }<br>  <br>  return true;<br>  <br> }<br> <br> public List getAll(){<br>  return null;<br> }<br> <br> public static void main(String[] args) {<br>  SessionFactory sessionFactory=null;<br>  try {<br>   sessionFactory=new Configuration().configure().buildSessionFactory();<br>   UserDao ud=new UserDao();<br>   UserModel um=new UserModel();<br>   um.setName("xyb");<br>   um.setAge(new Integer(10));<br>   ud.create(um, sessionFactory);<br>  } catch (HibernateException e) {<br>   e.printStackTrace();<br>  }<br>  <br> }<br>}</p> <p> </p> <p> </p> <p>运行后就报错,</p> <p>net.sf.hibernate.MappingException: Error reading resource: cn/javass/model/UserModel.hbm.xml<br> at net.sf.hibernate.cfg.Configuration.addResource(Configuration.java:336)<br> at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:990)<br> at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:946)<br> at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:874)<br> at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:860)<br> at cn.javass.dao.UserDao.main(UserDao.java:38)<br>Caused by: net.sf.hibernate.MappingException: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect<br> at net.sf.hibernate.cfg.Configuration.addInputStream(Configuration.java:293)<br> at net.sf.hibernate.cfg.Configuration.addResource(Configuration.java:333)<br> ... 5 more<br>Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect<br> at org.dom4j.io.SAXReader.read(SAXReader.java:358)<br> at net.sf.hibernate.cfg.Configuration.addInputStream(Configuration.java:283)<br> ... 6 more</p> <p> </p> <p>我不知道我的UserModel.hbm.xml的配制文件哪个写错了,请大家帮我看看.谢谢!</p> <p> </p><br /><strong>问题补充:</strong><br />没有听明白<br /><strong>问题补充:</strong><br />两位兄弟,我用的是hibernate2,pan_java回答的肯定不对,但是hibernate2怎么去配的就不知道了,请指教<br /><strong>问题补充:</strong><br />兄弟们: <br />hibernate.cfg.xml <br />&lt;?xml version="1.0" encoding="utf-8"?&gt;&nbsp;&nbsp; <br />&lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 2.0//EN"&nbsp;&nbsp;&nbsp;&nbsp; <br />"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"&gt;&nbsp;&nbsp; <br />&lt;hibernate-configuration&gt; <br />&nbsp;&nbsp;&nbsp; &lt;session-factory&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="dialect"&gt;net.sf.hibernate.dialect.MySQLDialect&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.driver_class"&gt;org.gjt.mm.mysql.Driver&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.username"&gt;root&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.password"&gt;xybxyb&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.url"&gt;jdbc:mysql://localhost:3306/dhwebnms&lt;/property&gt; <br /> <br /> &lt;property name="show_sql"&gt;true&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp; &lt;/session-factory&gt; <br /> <br />&lt;/hibernate-configuration&gt; <br /> <br />就这样,然后我去SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory(); <br />运行结果是; <br />net.sf.hibernate.HibernateException: problem parsing configuration/hibernate.cfg.xml <br /> at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:935) <br /> at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:874) <br /> at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:860) <br /> at cn.javass.dao.UserDao.main(UserDao.java:41) <br />Caused by: net.sf.hibernate.MappingException: invalid configuration <br /> at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:931) <br /> ... 3 more <br />Caused by: org.xml.sax.SAXParseException: The content of element type "session-factory" is incomplete, it must match "(property*,mapping+,(class-cache|collection-cache|jcs-class-cache|jcs-collection-cache)*)". <br /> at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) <br /> at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) <br /> at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) <br /> at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) <br /> at org.apache.xerces.impl.dtd.XMLDTDValidator.handleEndElement(Unknown Source) <br /> at org.apache.xerces.impl.dtd.XMLDTDValidator.endElement(Unknown Source) <br /> at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source) <br /> at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) <br /> at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) <br /> at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) <br /> at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source) <br /> at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) <br /> at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source) <br /> at org.dom4j.io.SAXReader.read(SAXReader.java:339) <br /> at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:930) <br /> ... 3 more <br />请指点 <br /> <br /><br /><strong>问题补充:</strong><br />谢谢各位的帮忙,但是现在为什么插不进数据呀,运行不抛异常,数据库里面没有数据 <br />&lt;?xml version="1.0" encoding="utf-8"?&gt;&nbsp;&nbsp; <br />&lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 2.0//EN"&nbsp;&nbsp;&nbsp;&nbsp; <br />"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"&gt;&nbsp;&nbsp; <br />&lt;hibernate-configuration&gt; <br />&nbsp;&nbsp;&nbsp; &lt;session-factory&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="dialect"&gt;net.sf.hibernate.dialect.MySQLDialect&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.driver_class"&gt;org.gjt.mm.mysql.Driver&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.username"&gt;root&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.password"&gt;xxxxxx&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="connection.url"&gt;jdbc:mysql://localhost:3306/dhwebnms&lt;/property&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /> &lt;property name="connection.pool.size"&gt;1&lt;/property&gt; <br /> &lt;property name="statement_cache.size"&gt;25&lt;/property&gt; <br /> &lt;property name="jdbc.fetch_size"&gt;50&lt;/property&gt; <br /> &lt;property name="jdbc.batch_size"&gt;30&lt;/property&gt; <br /> <br /> &lt;property name="show_sql"&gt;true&lt;/property&gt; <br /> &lt;mapping resource="cn/javass/model/UserModel.hbm.xml" /&gt; <br /> <br />&nbsp;&nbsp;&nbsp; &lt;/session-factory&gt; <br /> <br />&lt;/hibernate-configuration&gt; <br /> <br /> <br />UserModel.hbm.xml <br />&lt;?xml version="1.0"?&gt; <br />&lt;!DOCTYPE hibernate-mapping PUBLIC <br />"-//Hibernate/Hibernate Mapping DTD 2.0//EN" <br />"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"&gt; <br />&lt;hibernate-mapping <br />package="org.hibernate.auction"&gt; <br />&lt;class name="cn.javass.model.UserModel" table="tbl_user"&gt; <br />&nbsp; &lt;id name="uuid" type="java.lang.Integer"&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;column name="uuid" /&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;generator class="native" /&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/id&gt; <br />&nbsp; &lt;property name="name"/&gt; <br />&nbsp; &lt;property name="age"/&gt; <br />&lt;/class&gt; <br />&nbsp; <br />&lt;/hibernate-mapping&gt; <br />运行的语句 <br />SessionFactory sessionFactory=null; <br /> try { <br /> <br /> sessionFactory=new Configuration().configure().buildSessionFactory(); <br /> UserDao ud=new UserDao(); <br /> UserModel um=new UserModel(); <br /> um.setName("xyb"); <br /> um.setAge(new Integer(10)); <br /> ud.create(um, sessionFactory); <br /> } catch (HibernateException e) { <br /> e.printStackTrace(); <br /> } <br />数据库中没有值<br /><strong>问题补充:</strong><br />不好意思,我说的不报错,其实错:错误为 <br />se===&gt;net.sf.hibernate.impl.SessionImpl@157aa53 <br />net.sf.hibernate.JDBCException: Cannot open connection <br /> at net.sf.hibernate.impl.BatcherImpl.openConnection(BatcherImpl.java:281) <br /> at net.sf.hibernate.impl.SessionImpl.connect(SessionImpl.java:3302) <br /> at net.sf.hibernate.impl.SessionImpl.connection(SessionImpl.java:3282) <br /> at net.sf.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:40) <br /> at net.sf.hibernate.transaction.JDBCTransactionFactory.beginTransaction(JDBCTransactionFactory.java:19) <br /> at net.sf.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:2227) <br /> at cn.javass.dao.UserDao.create(UserDao.java:22) <br /> at cn.javass.dao.UserDao.main(UserDao.java:48) <br />Caused by: java.sql.SQLException: Communication failure during handshake. Is there a server running on localhost:3306? <br /> at org.gjt.mm.mysql.MysqlIO.init(MysqlIO.java:327) <br /> at org.gjt.mm.mysql.Connection.connectionInit(Connection.java:261) <br /> at org.gjt.mm.mysql.jdbc2.Connection.connectionInit(Connection.java:89) <br /> at org.gjt.mm.mysql.Driver.connect(Driver.java:167) <br /> at java.sql.DriverManager.getConnection(DriverManager.java:525) <br /> at java.sql.DriverManager.getConnection(DriverManager.java:140) <br /> at net.sf.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:101) <br /> at net.sf.hibernate.impl.BatcherImpl.openConnection(BatcherImpl.java:278) <br /> ... 7 more <br /><br /><strong>问题补充:</strong><br />我启动了mysql,也开启了事务 <br />public class UserDao { <br /> public boolean&nbsp; create(UserModel um,SessionFactory sf){ <br /> Session se=null; <br /> Transaction tx=null; <br /> try{ <br /> se=sf.openSession(); <br /> System.out.println("se===&gt;"+se); <br /> tx=se.beginTransaction(); <br /> se.save(um); <br /> tx.commit(); <br /> se.close(); <br /> }catch(Exception e){ <br /> e.printStackTrace(); <br /> return false; <br /> } <br /> <br /> return true; <br /> <br /> } <br /> <br /> <br /> <br /> public static void main(String[] args) { <br /> SessionFactory sessionFactory=null; <br /> try { <br /> <br /> sessionFactory=new Configuration().configure().buildSessionFactory(); <br /> UserDao ud=new UserDao(); <br /> UserModel um=new UserModel(); <br /> um.setName("xyb"); <br /> um.setAge(new Integer(10)); <br /> ud.create(um, sessionFactory); <br /> } catch (HibernateException e) { <br /> e.printStackTrace(); <br /> } <br /> <br /> } <br />}<br /><strong>问题补充:</strong><br />mysql我重新启动了,没有问题,用的端口也3306,我安的mysql版本是mysql-5.1.34-win32.msi,我用mysql-gui-tools-5.0-r17-win32.msi我也不知道是不是mysql的版本原因<br /><strong>问题补充:</strong><br />我觉得也是 <br />我想问一下大家:我现在用的驱动是mm.mysql-2.0.4-bin.jar <br />我知道还有一个驱动是mysql-connector-java-3.0.16-ga-bin.jar这两者之间有什么区别,如果我用第二个,那么我的hibernate.cfg.xml真不好意思,麻烦大家这么长时间.<br /><strong>问题补充:</strong><br />各们兄弟,问题找到了,从十点到现在一直在找这个问题,终于找到问题了,我换了一个驱动就行了,以前用mm.mysql-2.0.4-bin.jar ,现在改成了mysql-connector-java-3.0.16-ga-bin.j就能运行,在hibernate.cfg.xml里面改了一下就行了,特别感谢lovewhzlq兄弟.能留下你的qq吗,以后有什么问题请教你。但是为什么用mm.mysql-2.0.4-bin.jar 不行,我也不知道,如果谁知道了,请分享一下.<br /><strong>问题补充:</strong><br />主要是项目中都用那个,我也不是领导,别人这样用,我只能这样用了

在eclipse中运行Hibernate,出现Autocommit mode: false错误

我的Hibernate版本是:5.2.2以下是代码与错误提示 no1 一月 13, 2017 9:25:47 下午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.2.2.Final} 一月 13, 2017 9:25:47 下午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 一月 13, 2017 9:25:47 下午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist no2 一月 13, 2017 9:25:47 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 一月 13, 2017 9:25:47 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time. 一月 13, 2017 9:25:48 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) 一月 13, 2017 9:25:48 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql:///testhibernate] 一月 13, 2017 9:25:48 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} 一月 13, 2017 9:25:48 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:36) at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20) at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) at org.hibernate.boot.MetadataSources.buildMetadata(MetadataSources.java:179) at com.hibernate.test1.test.main(test.java:17) --------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///testhibernate</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> <mapping resource="com/hibernate/bean/LoginBean.hbm.xml"/> </session-factory> </hibernate-configuration> ----------------------------------------------------------- package com.hibernate.test1; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class test { public static void main(String[] args) { // TODO Auto-generated method stub StandardServiceRegistry registry=new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionfactory=new MetadataSources(registry).buildMetadata().buildSessionFactory(); Session session=sessionfactory.openSession(); Transaction transaction=session.beginTransaction(); log log1=new log(); log1.setName("nihao"); log1.setPass("dkjk"); session.save(log1); transaction.commit(); } } ----------------------------------------------- <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2017-1-13 18:13:48 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="com.hibernate.test.log" table="LOG"> <id name="name" type="java.lang.String"> <column name="NAME" /> <generator class="assigned" /> </id> <property name="pass" type="java.lang.String"> <column name="PASS" /> </property> </class> </hibernate-mapping>

Struts2+Hibernate单独运行都正确,联合起来就会出错 org.hibernate.MappingNotFoundException:

hibernate单独运行 ![图片说明](https://img-ask.csdn.net/upload/201701/14/1484377915_238337.png) Struts2单独运行 ![图片说明](https://img-ask.csdn.net/upload/201701/14/1484378154_361521.png) ![图片说明](https://img-ask.csdn.net/upload/201701/14/1484378167_615436.png) ![图片说明](https://img-ask.csdn.net/upload/201701/14/1484378180_771110.png) 联合运行 ![图片说明](https://img-ask.csdn.net/upload/201701/14/1484378034_851466.png) mysql 表结构 ![图片说明](https://img-ask.csdn.net/upload/201701/14/1484378276_313085.png) 贴错误信息: 一月 14, 2017 3:07:15 下午 org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml 一月 14, 2017 3:07:15 下午 org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: /hibernate.cfg.xml 一月 14, 2017 3:07:15 下午 org.hibernate.cfg.Configuration addResource INFO: HHH000221: Reading mappings from resource: entity/users.hbm.xml 一月 14, 2017 3:07:15 下午 org.hibernate.cfg.Configuration addResource INFO: HHH000221: Reading mappings from resource: entity/students.hbm.xml org.hibernate.MappingNotFoundException: resource: entity/students.hbm.xml not found at org.hibernate.cfg.Configuration.addResource(Configuration.java:728) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2109) at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2081) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2061) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2014) at org.hibernate.cfg.Configuration.configure(Configuration.java:1929) at org.hibernate.cfg.Configuration.configure(Configuration.java:1908) at db.MyHibernateSessionFactory.getSessionFactory(MyHibernateSessionFactory.java:18) at service.impl.UsersDAOImpl.usersLogin(UsersDAOImpl.java:21) at action.UsersAction.login(UsersAction.java:19) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) login_failure Users [uid=0, username=张三, password=123456]

关于hibernate的问题,求解答

myeclipse运行一个简单的JavaProject时出现了下面的异常: Exception in thread "main" java.lang.UnsupportedClassVersionError: org/hiber nate/cfg/Configuration : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at com.jxk.hibernate.Base.main(Base.java:13) 怎么解决啊啊

hibernate使用select ifnull报错但是在mysql直接运行没问题

String sql = "select ifnull(pushtoken,0) from user where id="+user.getId(); Session session = this.getHibernateTemplate().getSessionFactory() .openSession(); Query q = session.createSQLQuery(sql); List list = q.list(); 查询的时候报错 [10:40:59|INFO |(org.hibernate.type.StringType)]=[could not read column value from result set: ; Column '' not found.] [10:40:59|WARN |(org.hibernate.util.JDBCExceptionReporter)]=[SQL Error: 0, SQLState: S0022] [10:40:59|ERROR|(org.hibernate.util.JDBCExceptionReporter)]=[Column '' not found.] org.hibernate.exception.SQLGrammarException: could not execute query

Hibernate的executeSQLQuery问题

用的hibernate版本是3。运行环境是jboss4+ejb2。 问题描述:普通的HQL没问题,通过执行executeSQLQuery,比如对应的SQL是 select c.xx1,c.xx2,a.xx1 from c,a on c.id = a.id 正常返回是Object[],这个Object[]长度为3. 真实问题是:返回的是Object[],但是长度为0,直接抓狂。。。。。。 hibernate.cfg.xml: <session-factory> <property name="hibernate.session_factory_name">HibernateSessionFactory</property> <!-- <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property> --> <property name="hibernate.connection.datasource">java:jdbc/oracle</property> <property name="show_sql">false</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup</property> <property name="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property> <property name="hibernate.jdbc.fetch_size">50</property> <property name="hibernate.jdbc.batch_size">50</property> <property name="hibernate.transaction.auto_close_session">true</property> <property name="hibernate.transaction.flush_before_completion">false</property> <property name="hibernate.connection.release_mode">auto</property> <property name="hibernate.cache.use_second_level_cache">false</property> <property name="hibernate.cache.use_query_cache">false</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

java SSH项目,运行一段时间后报错,重启tomcat也报错,重启服务器后恢复正常,附上报错信息,求高手解答

## # 运行时报错信息: HTTP Status 500 – Internal Server Error Type 异常报告 消息 Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection 描述 服务器遇到一个意外的情况,阻止它完成请求。 Exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:943) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822) javax.servlet.http.HttpServlet.service(HttpServlet.java:634) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) Root Cause org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:517) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) rmyh.attendance.dao.LoginDao$$EnhancerByCGLIB$$7b46259f.checkLogin(<generated>) rmyh.attendance.service.LoginService.checkLogin(LoginService.java:89) rmyh.attendance.service.LoginService.login(LoginService.java:54) rmyh.attendance.controller.LoginController.login(LoginController.java:36) sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822) javax.servlet.http.HttpServlet.service(HttpServlet.java:634) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) Root Cause org.hibernate.exception.GenericJDBCException: Could not open connection org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54) org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:221) org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157) org.hibernate.internal.SessionImpl.connection(SessionImpl.java:550) org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:431) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) rmyh.attendance.dao.LoginDao$$EnhancerByCGLIB$$7b46259f.checkLogin(<generated>) rmyh.attendance.service.LoginService.checkLogin(LoginService.java:89) rmyh.attendance.service.LoginService.login(LoginService.java:54) rmyh.attendance.controller.LoginController.login(LoginController.java:36) sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822) javax.servlet.http.HttpServlet.service(HttpServlet.java:634) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) Root Cause java.sql.SQLException: An SQLException was provoked by the following failure: com.mchange.v2.resourcepool.ResourcePoolException: Attempted to use a closed or broken resource pool com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118) com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77) com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:74) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:691) com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140) org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141) org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292) org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214) org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157) org.hibernate.internal.SessionImpl.connection(SessionImpl.java:550) org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:431) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) rmyh.attendance.dao.LoginDao$$EnhancerByCGLIB$$7b46259f.checkLogin(<generated>) rmyh.attendance.service.LoginService.checkLogin(LoginService.java:89) rmyh.attendance.service.LoginService.login(LoginService.java:54) rmyh.attendance.controller.LoginController.login(LoginController.java:36) sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822) javax.servlet.http.HttpServlet.service(HttpServlet.java:634) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) Root Cause com.mchange.v2.resourcepool.ResourcePoolException: Attempted to use a closed or broken resource pool com.mchange.v2.resourcepool.BasicResourcePool.ensureNotBroken(BasicResourcePool.java:1735) com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:573) com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682) com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140) org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141) org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292) org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214) org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157) org.hibernate.internal.SessionImpl.connection(SessionImpl.java:550) org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:431) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) rmyh.attendance.dao.LoginDao$$EnhancerByCGLIB$$7b46259f.checkLogin(<generated>) rmyh.attendance.service.LoginService.checkLogin(LoginService.java:89) rmyh.attendance.service.LoginService.login(LoginService.java:54) rmyh.attendance.controller.LoginController.login(LoginController.java:36) sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822) javax.servlet.http.HttpServlet.service(HttpServlet.java:634) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) ## 重启tomcat报错信息: 严重: 初始化组件[Connector[HTTP/1.1-8080]]失败。 org.apache.catalina.LifecycleException: Protocol handler initialization failed at org.apache.catalina.connector.Connector.initInternal(Connector.java:983) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) at org.apache.catalina.core.StandardService.initInternal(StandardService.java:533) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:1059) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) at org.apache.catalina.startup.Catalina.load(Catalina.java:584) at org.apache.catalina.startup.Catalina.load(Catalina.java:607) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:304) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474) Caused by: java.io.IOException: Unable to establish loopback connection at sun.nio.ch.PipeImpl$Initializer.run(Unknown Source) at sun.nio.ch.PipeImpl$Initializer.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.nio.ch.PipeImpl.<init>(Unknown Source) at sun.nio.ch.SelectorProviderImpl.openPipe(Unknown Source) at java.nio.channels.Pipe.open(Unknown Source) at sun.nio.ch.WindowsSelectorImpl.<init>(Unknown Source) at sun.nio.ch.WindowsSelectorProvider.openSelector(Unknown Source) at java.nio.channels.Selector.open(Unknown Source) at org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector(NioSelectorPool.java:52) at org.apache.tomcat.util.net.NioSelectorPool.close(NioSelectorPool.java:119) at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:367) at org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup(AbstractEndpoint.java:1124) at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:1132) at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:557) at org.apache.coyote.http11.AbstractHttp11Protocol.init(AbstractHttp11Protocol.java:74) at org.apache.catalina.connector.Connector.initInternal(Connector.java:980) ... 13 more Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): bind at sun.nio.ch.Net.bind0(Native Method) at sun.nio.ch.Net.bind(Unknown Source) at sun.nio.ch.Net.bind(Unknown Source) at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source) at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source) at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source) at sun.nio.ch.PipeImpl$Initializer$LoopbackConnector.run(Unknown Source) ... 30 more 二月 20, 2020 3:38:12 下午 org.apache.coyote.AbstractProtocol init 信息: 初始化协议处理器 ["ajp-nio-8009"] 二月 20, 2020 3:38:12 下午 org.apache.catalina.util.LifecycleBase handleSubClassException 严重: 初始化组件[Connector[AJP/1.3-8009]]失败。 org.apache.catalina.LifecycleException: Protocol handler initialization failed at org.apache.catalina.connector.Connector.initInternal(Connector.java:983) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) at org.apache.catalina.core.StandardService.initInternal(StandardService.java:533) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:1059) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) at org.apache.catalina.startup.Catalina.load(Catalina.java:584) at org.apache.catalina.startup.Catalina.load(Catalina.java:607) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:304) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474) Caused by: java.io.IOException: Unable to establish loopback connection at sun.nio.ch.PipeImpl$Initializer.run(Unknown Source) at sun.nio.ch.PipeImpl$Initializer.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.nio.ch.PipeImpl.<init>(Unknown Source) at sun.nio.ch.SelectorProviderImpl.openPipe(Unknown Source) at java.nio.channels.Pipe.open(Unknown Source) at sun.nio.ch.WindowsSelectorImpl.<init>(Unknown Source) at sun.nio.ch.WindowsSelectorProvider.openSelector(Unknown Source) at java.nio.channels.Selector.open(Unknown Source) at org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector(NioSelectorPool.java:52) at org.apache.tomcat.util.net.NioSelectorPool.close(NioSelectorPool.java:119) at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:367) at org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup(AbstractEndpoint.java:1124) at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:1132) at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:557) at org.apache.catalina.connector.Connector.initInternal(Connector.java:980) ... 13 more Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): bind at sun.nio.ch.Net.bind0(Native Method) at sun.nio.ch.Net.bind(Unknown Source) at sun.nio.ch.Net.bind(Unknown Source) at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source) at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source) at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source) at sun.nio.ch.PipeImpl$Initializer$LoopbackConnector.run(Unknown Source) ... 29 more 二月 20, 2020 3:38:12 下午 org.apache.catalina.startup.Catalina load 信息: 服务器在[472]毫秒内初始化 二月 20, 2020 3:38:12 下午 org.apache.catalina.core.StandardService startInternal 信息: Starting service [Catalina] 二月 20, 2020 3:38:12 下午 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet engine: [Apache Tomcat/9.0.20] 二月 20, 2020 3:38:14 下午 org.apache.catalina.core.ApplicationContext log 信息: No Spring WebApplicationInitializer types detected on classpath 二月 20, 2020 3:38:15 下午 org.apache.jasper.servlet.TldScanner scanJars 信息: 至少有一个JAR被扫描用于TLD但尚未包含TLD。 为此记录器启用调试日志记录,以获取已扫描但未在其中找到TLD的完整JAR列表。 在扫描期间跳过不需要的JAR可以缩短启动时间和JSP编译时间。 二月 20, 2020 3:38:15 下午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext ## hibernate配置信息: ``` <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="connection.characterEncoding">UTF-8</property> <property name="hibernate.autoReconnect">true</property> </session-factory> </hibernate-configuration> ``` ## c3p0配置信息: ``` <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/attendance?useUnicode=true&serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf8&useOldAliasMetadataBehavior=true&autoReconnect=true"></property> <property name="initialPoolSize" value="10"></property> <property name="minPoolSize" value="10" /> <property name="maxPoolSize" value="512"></property> <property name="idleConnectionTestPeriod" value="2800"></property> <property name="maxIdleTime" value="180"></property> <property name="maxStatements" value="1000" /> <property name="acquireIncrement" value="5" /> <property name="acquireRetryAttempts" value="30"></property> <property name="breakAfterAcquireFailure" value="true"></property> <property name="testConnectionOnCheckout" value="false"></property> </bean> ```

Hibernate4创建SessionFactory时卡住不运行?

Hibernate4创建SessionFactory时卡住不运行? 使用Hibernate4写一个CRUD示例,javase程序,在main方法中创建sessionFactory,使用如下代码: private HibernateUtils() { try { if (this.sessionFactory == null) { Configuration cfg = new Configuration(); cfg.configure(new File("hibernate.cfg.xml")); cfg.setNamingStrategy(ImprovedNamingStrategy.INSTANCE); ServiceRegistry sr =new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); this.sessionFactory = cfg.addAnnotatedClass(ApplyInfo.class) .addAnnotatedClass(Contract.class) .addAnnotatedClass(Overview.class) .addAnnotatedClass(SegmentHtml.class) .buildSessionFactory(sr); } } catch (Exception e) { e.printStackTrace(); throw e; } } 在Eclipse中普通运行就会卡住不允许,如果是debug方式运行,就没有任何问题. 卡在如下日志处 五月 13, 2014 10:34:16 上午 org.hibernate.annotations.common.Version <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final} 五月 13, 2014 10:34:16 上午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.2.12.Final} 五月 13, 2014 10:34:16 上午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 五月 13, 2014 10:34:16 上午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 五月 13, 2014 10:34:16 上午 org.hibernate.cfg.Configuration configure INFO: HHH000042: Configuring from file: hibernate.cfg.xml 五月 13, 2014 10:34:17 上午 org.hibernate.cfg.Configuration doConfigure INFO: HHH000041: Configured SessionFactory: null 五月 13, 2014 10:34:17 上午 org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator getConfiguredConnectionProviderName WARN: HHH000208: org.hibernate.connection.C3P0ConnectionProvider has been deprecated in favor of org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider; that provider will be used instead. 五月 13, 2014 10:34:17 上午 org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider 五月 13, 2014 10:34:17 上午 org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure INFO: HHH010002: C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/pgdata 五月 13, 2014 10:34:17 上午 org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure INFO: HHH000046: Connection properties: {user=root, password=****} 五月 13, 2014 10:34:17 上午 org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure 这句 org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure​ 到这里就不在向下执行.在Debug模式就没有任何问题,创建SessionFactory和Crud都正常. 数据库驱动,hibernate4小版本号够尝试换成别的版本,都没能解决问题. 请大家指教!谢谢

hibernate整合redis二级缓存问题

背景: 有一老项目采用的hibernate配合ehcache作为二级缓存,现因需求需要更换redis来做hibernate的二级缓存。大家不用问为什么不换掉hibernate,因为是老项目所以风险太大。 问题: 1、我按照网上做法导入了若干个jar包,见图: ![图片说明](https://img-ask.csdn.net/upload/201809/12/1536736237_134115.jpg) 2、spring中sessionFactory也配置了二级缓存: ``` hibernate.cache.use_query_cache = true hibernate.cache.use_second_level_cache = true hibernate.cache.use_structured_entries = true hibernate.cache.region_prefix = hibernate hibernate.cache.region.factory_class = org.hibernate.cache.redis.hibernate5.RedisRegionFactory hibernate.cache.provider_configuration_file_resource_path = hibernate-redis.properties ``` 3、也分别创建了hibernate-redis.properties和redisson.yaml,内容分别如下 (1)hibernate-redis.properties: ``` redisson-config = classpath:redisson.yaml redis.expiryInSeconds.default = 360 redis.expiryInSeconds.hibernate.common = 0 redis.expiryInSeconds.hibernate.account = 1200 ``` (2)redisson.yaml ``` singleServerConfig: idleConnectionTimeout: 10000 pingTimeout: 5000 connectTimeout: 5000 timeout: 5000 retryAttempts: 1 retryInterval: 1000 reconnectionTimeout: 3000 failedAttempts: 1 password: 123456 subscriptionsPerConnection: 3 clientName: null address: [ "redis://127.0.0.1:6379" ] subscriptionConnectionMinimumIdleSize: 1 subscriptionConnectionPoolSize: 3 connectionMinimumIdleSize: 3 connectionPoolSize: 3 database: 0 dnsMonitoring: false dnsMonitoringInterval: 5000 threads: 0 codec: !<org.redisson.codec.SnappyCodec> {} useLinuxNativeEpoll: false eventLoopGroup: null ``` 4、redis也正常运行 5、最后运行程序报了一个错: ``` Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.net.URI` out of START_ARRAY token at [Source: (URL); line: 14, column: 4] (through reference chain: org.redisson.config.Config["singleServerConfig"]->org.redisson.config.SingleServerConfig["address"]) at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1138) at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromArray(StdDeserializer.java:674) at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.deserialize(FromStringDeserializer.java:164) at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:136) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151) at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2959) at org.redisson.config.ConfigSupport.fromYAML(ConfigSupport.java:169) at org.redisson.config.Config.fromYAML(Config.java:754) at org.hibernate.cache.redis.client.RedisClientFactory.createRedisClient(RedisClientFactory.java:63) ... 57 more ``` 不知道怎么解决了,希望有相关经验的大神能助我解惑。

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

C++(数据结构与算法)78:---分而治之

一、分而治之的思想 分而治之方法与软件设计的模块化方法非常相似 分而治之通常不用于解决问题的小实例,而要解决一个问题的大实例。一般步骤为: ①把一个大实例分为两个或多个更小的实例 ②分别解决每个小实例 ③把这些小实例的解组合成原始大实例的解 二、实际应用之找出假币 问题描述 一个袋子有16个硬币,其中只有一个是假币,这个假币比其他的真币重量轻(其他所有真币的重量都是相同的)...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

立即提问
相关内容推荐