关于spring+hibernate 注入sessionFactory为null的问题

最近一个项目需要用到struts2+spring+hibernate组合框架,我在一点一点的做配置,但做到注入SessionFactory时,一直不成功,在网上搜的一些解决方案也都不适用。故在此发布,希望高手们不吝赐教。
web.xml的配置为:

       <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

        <display-name>bae</display-name>

        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application-context.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

application-context.xml有内容为:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.test"/>
    <context:annotation-config />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl">update</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.test.modal.Test</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

</beans>

用到的jar包为:
CSDN移动问答

在代码中使用方式为:

    @Resource
    private SessionFactory sessionFactory;

    @Test
    public void test(){
        System.out.println(sessionFactory);
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

此时打印出来的值为null.

suannai0314
鹳狸媛 楼主的这个问题解决了么?下边的答案能解决问题么?如果可以麻烦点击答案旁的√采纳哦~如果没有也可以将自己的答案贴上然后进行采纳的。
6 年多之前 回复

4个回答

改成@Autowired 我这边还是不会注入。悲催的我

跟注释没有关系的。你不信试试。这个问题也困扰我好久了

一直都是@autowired,注入不了啊!!!

干嘛用@Resource,用@Autwired。

zhurizhiyiing
最爱海贼王 神回复!改了立马就绿了!!!
接近 6 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于spring+hibernate 注入sessionFactory为null的问题

最近一个项目需要用到struts2+spring+hibernate组合框架,我在一点一点的做配置,但做到注入SessionFactory时,一直不成功,在网上搜的一些解决方案也都不适用。故在此发布,希望高手们不吝赐教。 web.xml的配置为: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>bae</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> application-context.xml有内容为: <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.test"/> <context:annotation-config /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/test"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl">update</prop> </props> </property> <property name="annotatedClasses"> <list> <value>com.test.modal.Test</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans> 用到的jar包为: ![CSDN移动问答][1] 在代码中使用方式为: @Resource private SessionFactory sessionFactory; @Test public void test(){ System.out.println(sessionFactory); } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } 此时打印出来的值为null. [1]: http://d.pcs.baidu.com/thumbnail/943f3dabdf29e7a1f361203f6efa438e?fid=3591350289-250528-3777730014&time=1383623281&sign=FDTAR-DCb740ccc5511e5e8fedcff06b081203-cJUDS2H3PFGm8jal1yEtiblRSCM=&rt=sh&expires=8h&r=609927047&size=c710_u500&quality=100

hibernate4.3.5中使用spring4.0.0注入sessionFactory出现null

最近在搞SSH整合,遇到问题了,就是spring注入sessionFactory失败 报错如下 type Exception report message description The server encountered an internal error that prevented it from fulfilling this request. exception java.lang.NullPointerException com.victor.dao.impl.BaseDaoImpl.getSession(BaseDaoImpl.java:46) com.victor.dao.impl.BaseDaoImpl.search(BaseDaoImpl.java:56) com.victor.dao.impl.UserDaoImpl.isValidte(UserDaoImpl.java:16) com.victor.actions.LoginAction.execute(LoginAction.java:23) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149)

Spring 注解注入 SessionFactory 空指针异常

# Spring 注解注入 SessionFactory 空指针异常 条件一 applicationContext.xml文件已经配置了SessionFactory ``` <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 引用上面的dataSource配置数据库 --> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- Hibernate的一些属性配置 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><!-- Hibernate的配置方言 --> <prop key="hibernate.show_sql">true</prop><!-- Hibernate生成的sql语句是否显示 --> </props> </property> <property name="mappingResources"> <list> <value>com/bigfire/entity/Sale.hbm.xml</value> </list> </property> ``` 条件二 SessionFactory 已经成功注入到Spring容器中, ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml"); String[] str=act.getBeanDefinitionNames(); for (String string : str) { System.out.println("..."+string); } ![图片说明](https://img-ask.csdn.net/upload/201808/27/1535361242_671235.png) 这个问题我百度了两天了,有些方法也都试过了,哪位同学解决了麻烦给分享下解决的办法,谢谢了

spring获取不到hibernate的sessionFactory

错误信息如下 信息: Initializing Spring root WebApplicationContext - Root WebApplicationContext: initialization started - Refreshing Root WebApplicationContext: startup date [Thu Mar 30 21:02:38 CST 2017]; root of context hierarchy - Loading XML bean definitions from file [D:\apache-tomcat-7.0.47\webapps\WorkOrder\WEB-INF\classes\applicationContext.xml] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@78f77c8e: defining beans [sessionFactory,txManager,txAdvice,org.springframework.aop.config.internalAutoProxyCreator,pointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0]; root of factory hierarchy - Hibernate Commons Annotations 3.2.0.Final - Hibernate 3.6.8.Final - hibernate.properties not found - Bytecode provider name : javassist - using JDK 1.4 java.sql.Timestamp handling - configuring from url: file:/D:/apache-tomcat-7.0.47/webapps/WorkOrder/WEB-INF/classes/hibernate.cfg.xml - Configured SessionFactory: null - Hibernate Validator not found: ignoring - Building new Hibernate SessionFactory - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled. - Using Hibernate built-in connection pool (not for production use!) - Hibernate connection pool size: 20 - autocommit mode: false - using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@localhost:1521:orcl - connection properties: {user=system, password=****} - Using dialect: org.hibernate.dialect.Oracle10gDialect - Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException - Database -> 下面是hibernate <?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="javax.persistence.validation.mode">none</property> <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">system</property> <property name="connection.password">a123</property> <property name="dialect"> org.hibernate.dialect.Oracle10gDialect </property> <property name="show_sql">true</property> <property name="format_sql">true</property> </session-factory> </hibernate-configuration> 下面是spring <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean>

用spring注入sessionfactory,总是null,请教大家帮我看看是什么问题

用ssh做的一个小东西,写了泛型dao,然后继承了hibernatedaosupport,然而 在方法里面用getHibnerateTemplate()时总是null。 我用main方法测试都是成功注入的,还有在其它地方自己new一个然后传入sessionFactory,输出sessionFactory和getHibneratemTemplate都是有值的,但是进入方法总是null,我试了一天都解决不了。 前提:我的所有包都引入好了,包括互相协调的包,由于太多,我就贴了一些相关的方法代码,请大家帮我看看。 另外,还有没有更好的写法?或者比hibernateDaoSupport更好用的模板,有的话,请指点一下,谢谢 这个是BaseDao public interface BaseDao<T extends Serializable , ID extends Serializable> { void save(T entity); void update(T entity); List<T> findAll(Class<T> entityClass); ``` ``` 这是BaseDaoImpl public class BaseDaoImpl<T extends Serializable , ID extends Serializable> extends HibernateDaoSupport implements BaseDao<T, ID> { @Override public void save(T entity) { getHibernateTemplate().save(entity); } @Override public void update(T entity) { getHibernateTemplate().update(entity); @Override public List<T> findAll(Class<T> entityClass) { String hql = "from " + entityClass; System.out.println("template---"+getHibernateTemplate()); System.out.println("hql---"+hql); System.out.println("sessionFactory---"+super.getSessionFactory()); return (List<T>)getHibernateTemplate().find(hql); } ``` ``` 这是BaseService public interface BaseService<T extends Serializable , ID extends Serializable> { void save(T entity); void update(T entity); List<T> findAll(Class<T> entityClass); ``` ``` 这是BaseServiceImpl public class BaseServiceImpl<T extends Serializable , ID extends Serializable> implements BaseService<T, ID> { private BaseDao<T , ID> baseDao; public void setBaseDao(BaseDao<T , ID> baseDao){ this.baseDao = baseDao; } @Override public void save(T entity) { baseDao.save(entity); } @Override public void update(T entity) { baseDao.update(entity); } @Override public List<T> findAll(Class<T> entityClass) { return baseDao.findAll(entityClass); } ``` ``` 这是web.xml <filter> <filter-name>Struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>Struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> ``` ``` 这是applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <bean id="baseDaoImpl" class="com.lamp.dao.impl.BaseDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> ```<bean name="showAllContactAction" class="com.lamp.action.ShowAllContactAction" scope="prototype"> <property name="contactServiceImpl"> <bean class="com.lamp.service.impl.ContactServiceImpl"></bean> </property> </bean> ``` 这是action的代码 public class ShowAllContactAction extends ActionSupport{ private List<Contact> resultAllContactList; private ContactServiceImpl contactServiceImpl; public void setContactServiceImpl(ContactServiceImpl contactServiceImpl){ this.contactServiceImpl = contactServiceImpl; } public String execute(){ resultAllContactList = contactServiceImpl.findAll(Contact.class); ActionContext.getContext().put("resultAllContactList" , resultAllContactList); return "SUCCESS"; } } ``` ``` 这是hibernate配置文件 <hibernate-configuration> <session-factory> <property name="show_sql">true</property> <property name="connection.url">jdbc:mysql://localhost:3306/sanke_daily</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/lamp/entity/Contact.hbm.xml"/> </session-factory> </hibernate-configuration> 这是struts.xml <action name="showAllContactAction" class="showAllContactAction"> <result name="SUCCESS">/jsp/contact/showAllContactSuccess.jsp</result> </action> 另外,ContactBaseDao、ContactBaseDaoImpl和ContactService、ContactServiceImpl都没有新加的特别的方法,所以都是空的

使用springboot时注入SessionFactory报错

**将原来的一个web项目改成使用springboot时,启动时报错SessionFactory的bean找不到,具体信息如下,各位大佬帮忙看看吧。** web.xml: ``` <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/applicationContext.xml</param-value> </context-param> ``` applicationContext.xml: ``` <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="80" /> <property name="maxIdle" value="20" /> <property name="maxWait" value="30000" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> </props> </property> </bean> ShowConfigDaoImpl: ``` @Repository public class ShowConfigDaoImpl extends HibernateDaoSupport implements ShowConfigDao { @Autowired public SessionFactory sessionFactory; public Session getSession() { if (sessionFactory != null) { try { sessionFactory.close(); } catch (Exception e) { e.printStackTrace(); } } return sessionFactory.openSession(); } } ``` POM.XML: ``` <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> </dependencies> ``` 报错信息: ``` org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at com.tasd.demo.DemoApplication.main(DemoApplication.java:10) [classes/:na] ```

在springmvc+hibernate4整合,sessionfactory空指针

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in URL [file:/F:/apache-tomcat-7.0.57/webapps/MerchantService/WEB-INF/classes/config/beans.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:591) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1245) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1895) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) 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:745) Caused by: java.lang.NullPointerException at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:207) at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:73) at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2283) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2279) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1748) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1788) at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:189) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:350) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:335) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ... 25 more

hibernate中sessionFactory问题

一对多映射 感觉没错,求解啊!!! ``` public class HibernateUtil { private static SessionFactory sessionFactory; private static Session session; static { //创建configuration对象,读取hibernate.cfg.xml文件,完成初始化 Configuration config = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); sessionFactory = config.buildSessionFactory(serviceRegistry); //16 } //获取sessionFactory public static SessionFactory getSessionFactory() { return sessionFactory; } //获取session对象 public static Session getSession() { session = sessionFactory.openSession(); return session; } //关闭会话 public static void closeSession(Session session) { if(session!=null) { session.close(); } } } public class Test { public static void main(String[] args) { add(); //14 } //将学生添加到班级 public static void add() { Grade g = new Grade("java一班", "java软件开发一班"); Student s1 = new Student("张三", "男"); Student s2 = new Student("慕女神","女"); g.getStudents().add(s1); g.getStudents().add(s2); //保存班级、学生信息 Session session = HibernateUtil.getSession(); //29 Transaction transaction = session.beginTransaction(); session.save(g); session.save(s1); session.save(s2); transaction.commit(); HibernateUtil.closeSession(session); } } 错误信息: Exception in thread "main" java.lang.ExceptionInInitializerError at com.imooc.entity.Test.add(Test.java:29) at com.imooc.entity.Test.main(Test.java:14) Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185) at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:385) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790) at com.imooc.util.HibernateUtil.<clinit>(HibernateUtil.java:16) ... 2 more Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163) ... 6 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135) ... 15 more Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for student in class com.imooc.entity.Grade at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:316) at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:310) at org.hibernate.mapping.Property.getGetter(Property.java:321) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:444) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:200) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82) ... 20 more ```

关于spring 注入为null的一些问题

这是一个基于SSH框架的网站系统其中的登录模块,结果在登录的时候userserviceimpl始终是null 这个是DAO实现 ``` package dao; import entity.User; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class UserDAOImpl extends HibernateDaoSupport implements UserDAO { //增加用户 @Override public void addUser(User user){ getHibernateTemplate().save(user); } //查询验证用户是否存在 @Override public User findUser(User user){ User user1 = new User(); String hql = "from User user where user.username='" + user.getUsername() + "' and user.password= '" + user.getPassword() + "'"; //将查询出的结果放到List List<User> userlist = getHibernateTemplate().findByExample(user); //判断是否有查询结果,换句话说就是判断用户是否存在 if(userlist.size()>0){ //取出查询结果的第一个值 user1 = userlist.get(0); } return user1; } } ``` userService ``` package service; import dao.UserDAOImpl; import entity.User; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { //注入对象UserDAO private UserDAOImpl userdaoimpl; public void setUserDAOImpl(UserDAOImpl userdaoimpl) { this.userdaoimpl = userdaoimpl; } //保存用户信息 @Override public void addUser(User user){ this.userdaoimpl.addUser(user); } //查找验证用户信息 @Override public boolean findUser(User user){ User user1 = this.userdaoimpl.findUser(user); //DAO查询中已经判断当用户名密码都存在时才返回user1,这里只用判断用户名是否存在就行 if(user1.getUsername()!=null){ return true; }else{ return false; } } } ``` LoginAction ``` package action; import com.opensymphony.xwork2.ActionSupport; import entity.User; import org.springframework.beans.factory.annotation.Autowired; import service.UserService; import service.UserServiceImpl; public class LoginAction extends ActionSupport{ private User user; public void setUser(){ this.user=user; } private UserServiceImpl userserviceimpl; public void setUserServiceImpl(UserServiceImpl userserviceimpl) { this.userserviceimpl = userserviceimpl; } @Override public String execute() throws Exception{ boolean flag = userserviceimpl.findUser(user); if (flag) { return SUCCESS; } else { return INPUT; } } } ``` 配置文件 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <!-- dbcp连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/user_db"> </property> <property name="username" value="root"> </property> <property name="password" value="1234"> </property> </bean> <!--hibernate--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</prop> <prop key="hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">true</prop> </props> </property> <property name="mappingResources"> <list> <value>entity/User.hbm.xml</value> </list> </property> </bean> <!--使用属性注入--> <bean id="User" class="entity.User"></bean> <bean id="UserDAO" class="dao.UserDAOImpl" scope="singleton"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="UserService" class="service.UserServiceImpl" scope="prototype"> <property name="userDAOImpl" ref="UserDAO"></property> </bean> <bean id="action.RegistAction" class="action.RegistAction" scope="prototype"> <property name="UserServiceImpl" ref="UserService"></property> </bean> <bean id="action.LoginAction" class="action.LoginAction" scope="prototype"> <property name="UserServiceImpl" ref="UserService"></property> </bean> </beans> ``` 在LoginAction中 userserviceimpl总是null

Spring sessionFactory注入配置问题直接报容器错误,请大虾们看看

环境:spring 3.1 M2 + hibernate 3.6 web.xml [code="xml"]<!-- 自动装配ApplicationContext的配置信息--> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/classes/conf/hibernate.cfg.xml, /WEB-INF/classes/conf/beans.xml </param-value> </context-param> <display-name>springDemo</display-name> <servlet> <servlet-name>springDemo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:conf/applicationContext.xml </param-value> </init-param> <load-on-startup>1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDemo</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--初始化log4j --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/conf/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <!-- 防止内存泄漏,可选配置 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>[/code] applicationContext.xml [code="xml"] <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:conf/jdbc.properties</value> </list> </property> </bean> <!-- Choose the dialect that matches your "dataSource" definition --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${driverClassName}</value> <!--com.mysql.jdbc.Driver --> </property> <property name="url"> <value>${url}</value> <!--jdbc:mysql://localhost:3306/example --> </property> <property name="username"> <value>${username}</value> <!--root --> </property> <property name="password"> <value>${password}</value> <!--1234 --> </property> </bean> <!-- 配置Hibernate的sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- 配置事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- 配置事务代理 --> <bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="transactionAttributes"> <props> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> <!-- Default ViewResolver 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!-- 视图名称前缀和后缀 --> <property name="prefix" value="/web/"/> <property name="suffix" value=".jsp"></property> </bean> [/code] /WEB-INF/classes/conf/hibernate.cfg.xml, [code="xml"]<hibernate-configuration> <session-factory> <mapping resource="personal/learn/entity/Manager.hbm.xml" /> </session-factory> </hibernate-configuration>[/code] beans.xml [code="xml"] <bean id="simpleUrlHandlerMappingC" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/manager.do">manager</prop> </props> </property> </bean> <bean id="manager" class="personal.learn.hibernate.controller.ManagerController"> <property name="methodNameResolver" ref="ParameterMethodNameResolver"/> <property name="managerService" ref="managerService"/> </bean> <!-- 如果加上这个Dao的注入就会报错,后面的错语误 <bean id="managerDao" class="personal.learn.hibernate.dao.impl.ManagerDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> --> <bean id="managerService" class="personal.learn.hibernate.service.ManagerService"> <!-- <property name="managerDao" ref="managerDao"/> --> </bean>[/code] 错误码: [code="log"] Log4j:WARN No appenders could be found for logger (org.apache.commons.digester.Digester.sax). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. 2011-5-11 12:44:32 org.apache.catalina.core.StandardContext start 严重: Error listenerStart 2011-5-11 12:44:32 org.apache.catalina.core.StandardContext start 严重: Context [/springDemo] startup failed due to previous errors 2011-5-11 12:44:32 org.apache.coyote.http11.Http11BaseProtocol start 信息: Starting Coyote HTTP/1.1 on http-8080[/code] ManagerDaoImpl.java [code="java"] public class ManagerDaoImpl extends HibernateDaoSupport implements ManagerDao { @SuppressWarnings("unchecked") public List<Manager> findAll() { Criteria cri = this.getSession().createCriteria(Manager.class); return this.getHibernateTemplate().find("Select * from Manager"); } }[/code] ManagerService.java [code="java"]public class ManagerService extends BaseService{ private ManagerDao managerDao; public ManagerDao getManagerDao() { return managerDao; } public void setManagerDao(ManagerDao managerDao) { this.managerDao = managerDao; } public List<Manager> findAll(){ System.out.println("came here..."); return null; //return managerDao.findAll(); } }[/code] 如果不注入DAO 可控制台可以输出 came here.. 说明service 没有错

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小版本号够尝试换成别的版本,都没能解决问题. 请大家指教!谢谢

Spring bean注入 获取为空

<!--applicationContext.xml--> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/db_xyd?useUnicode=true&amp;amp;amp;amp;amp;amp;characterEncoding=utf-8-"> </property> <property name="username" value="root"></property> <property name="password" value="1234"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> <!-- org.hibernate.dialect.SQLServerDialect--> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/model/TDictionary.hbm.xml</value> </list> </property> </bean> <!-- dictionary --> <bean id="TDictionaryDAO" class="com.dao.TDictionaryDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="dictionaryAction" class="com.action.dictionaryAction" scope="prototype"> <property name="dictionaryDAO"> <ref bean="TDictionaryDAO" /> </property> </bean> </beans> package com.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.model.TDictionary; public class TDictionaryDAO extends HibernateDaoSupport { private static final Log log = LogFactory.getLog(TDictionaryDAO.class); public void save(TDictionary transientInstance) { log.debug("saving TDictionary instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public static TDictionaryDAO getFromApplicationContext(ApplicationContext ctx) { return (TDictionaryDAO) ctx.getBean("TDictionaryDAO"); } } package com.action; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.dao.TDictionaryDAO; import com.model.TDictionary; import com.opensymphony.xwork2.ActionSupport; public class dictionaryAction extends ActionSupport { private int OID; private String willtake; private TDictionaryDAO dictionaryDAO; public String dictionaryAdd() { TDictionary dict=new TDictionary(); dict.setOID(OID); dict.setL_key(100000); dict.setVc_value(willtake); dict.setVc_caption("vc_caption"); //这里报空指针异常,是dictionaryDAO空 dictionaryDAO.save(dict); return "success"; } public TDictionaryDAO getDictionaryDAO() { return dictionaryDAO; } public void setDictionaryDAO(TDictionaryDAO dictionaryDAO) { this.dictionaryDAO = dictionaryDAO; } }

ssh配置 sessionFactory依赖的jar包找不到

所有都是myeclipse自动生成的代码。 spring配置文件: ![图片说明](https://img-ask.csdn.net/upload/201806/02/1527938194_887948.png) 如果改成org.springframework.orm.hibernate4.LocalSessionFactoryBean 配置文件不报错了,但是通过sessionFactory获取的session为null。 是myeclipse的错误还是我操作的错误(少导或导错了jar包)? 怎么解决

Spring整合hibernate SessionFactoryImpl的问题

各位大侠,本人在整合Spring和Hibernate4时出现了Failed to convert property value of type 'org.hibernate.internal.SessionFactoryImpl' to required type 'org.hibernate.Session' for property 'sessionFactory'问题,我的applicationContext.xml如下: <bean id="employeeDao" class="com.ssh.dao.EmployeeDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="employeeService" class="com.ssh.service.EmployeeService"> <property name="employeeDao" ref="employeeDao"></property> </bean> <!-- 配置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="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- <context:component-scan base-package="com.ssh.*"></context:component-scan>--> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="classpath:com/ssh/entities/*.hbm.xml"></property> </bean> <!-- 配置xml声明式事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.ssh.service.*.*(..))" id="txPointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> Employee.java: public class EmployeeDao { private SessionFactory sessionFactory; public Session getSessionFactory() { return sessionFactory.getCurrentSession(); } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @SuppressWarnings("unchecked") public List<Employee> getAll(){ String hql = "FROM Employee"; return getSessionFactory().createQuery(hql).list(); } } EmployeeService.java: public class EmployeeService { private EmployeeDao employeeDao; public EmployeeDao getEmployeeDao() { return employeeDao; } public void setEmployeeDao(EmployeeDao employeeDao) { this.employeeDao = employeeDao; } public List<Employee> getAll(){ return employeeDao.getAll(); } } 测试类SSHTest.java: public class SSHTest { private ApplicationContext ctx = null; private EmployeeService employeeService; { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); employeeService = (EmployeeService) ctx.getBean("employeeService"); } @Test public void testEmployeeService() { System.out.println(employeeService.getAll()); } } 异常信息如下: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.hibernate.internal.SessionFactoryImpl' to required type 'org.hibernate.Session' for property 'sessionFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [org.hibernate.Session] for property 'sessionFactory': no matching editors or conversion strategy found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) 应该是applicationContext.xml中 配置的 <property name="sessionFactory" ref="sessionFactory"></property> 这一步对应的sessionFactory出错了。网上的例子这样是可以的。然后我把在xml配置bean改成用自动注入注解的方式配置结果就可以,请问这是为什么啊?

spring hibernate使用双数据源

配置了两个sessionfactory,在dao中使用getCurrentSession报错no current session in thread,用openSession报错org.hibernate.service.UnknownServiceException: Unknown service requested ,跟进去发现有一个tenantidentifier的变量为null。求大神解答怎么解决,试过好多方法都没办法解决。

SSH框架Hibernate基于Spring自动生成的DAO怎样使用

applicantContext.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx"> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="UserDAO" class="org.dao.UserDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> </beans> ``` 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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.url"> jdbc:mysql://localhost:3306/ </property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="myeclipse.connection.profile">mysql</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="cache.use_query_cache">true</property> <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property> <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property> <mapping resource="org/vo/User.hbm.xml" /> </session-factory> </hibernate-configuration> ``` UserDAO类 ``` public class UserDAO { private static final Logger log = LoggerFactory.getLogger(UserDAO.class); // property constants public static final String UNAME = "uname"; public static final String PASSWORD = "password"; private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private Session getCurrentSession() { return sessionFactory.getCurrentSession(); } protected void initDao() { // do nothing } public void save(User transientInstance) { log.debug("saving User instance"); try { getCurrentSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(User persistentInstance) { log.debug("deleting User instance"); try { getCurrentSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public User findById(java.lang.Integer id) { log.debug("getting User instance with id: " + id); try { User instance = (User) getCurrentSession().get("org.vo.User", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List<?> findByExample(User instance) { log.debug("finding User instance by example"); try { List<?> results = getCurrentSession().createCriteria("org.vo.User") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List<?> findByProperty(String propertyName, Object value) { log.debug("finding User instance with property: " + propertyName + ", value: " + value); try { String queryString = "from User as model where model." + propertyName + "= ?"; Query queryObject = getCurrentSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List<?> findByUname(Object uname) { return findByProperty(UNAME, uname); } public List<?> findByPassword(Object password) { return findByProperty(PASSWORD, password); } public List<?> findAll() { log.debug("finding all User instances"); try { String queryString = "from User"; Query queryObject = getCurrentSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public User merge(User detachedInstance) { log.debug("merging User instance"); try { User result = (User) getCurrentSession().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(User instance) { log.debug("attaching dirty User instance"); try { getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(User instance) { log.debug("attaching clean User instance"); try { getCurrentSession().buildLockRequest(LockOptions.NONE).lock( instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static UserDAO getFromApplicationContext(ApplicationContext ctx) { return (UserDAO) ctx.getBean("UserDAO"); } } ``` HibernateSessionFactory类 ``` public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } } ``` 测试类 ``` package org.action; import org.dao.UserDAO; import org.vo.User; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub // Session session = HibernateSessionFactory.getSession(); // session.beginTransaction(); // 插入数据 // session.save(new User("大傻", "123")); // 通过id查询数据 // User user = (User) session.load(User.class, 1); // System.out.println(user.getPassword()); // 通过id查找并删除数据 // User user = (User) session.get(User.class, 8); // session.delete(user); // 通过id查找并修改数据 // User user = (User) session.load(User.class, 9); // user.setPassword("999999"); // session.saveOrUpdate(user); // UserDAO userDAO = new UserDAO(); User user = new User("Jone", "111111"); userDAO.save(user); // session.getTransaction().commit(); // session.close(); } } ``` * 错误提示 ``` SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Exception in thread "main" java.lang.NullPointerException at org.dao.UserDAO.getCurrentSession(UserDAO.java:41) at org.dao.UserDAO.save(UserDAO.java:51) at org.action.Test.main(Test.java:40) ``` 第一行指向 ``` UserDAO的private Session getCurrentSession() { return sessionFactory.getCurrentSession(); } ``` 第二行错误指向 ``` public void save(User transientInstance) { log.debug("saving User instance"); try { # getCurrentSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } ```

在spring集成hibernate 中,如果包含中文参数查询不出结果

我的项目在spring4.3.5中集成hibernate4.3.11,其中如果包含中文参数查询不出任何结果 下面方法的参数username如果是字母可以正常读取到数据,如果是中文则uniqueResult为null。 我谷歌了网上说的都是使用setString 设置参数就不会有中文问题了,可我本来就是用的是setString方法设置参数的,请求各位大侠赐教 ``` @Override public void updateUserAccount(String username, int price) { // 验证余额是否足够 String hql = "select a.balance from Account a where a.username=?"; Object uniqueResult = getSession().createQuery(hql).setString(0, username).uniqueResult(); int balance = (int) uniqueResult; if (balance < price) { throw new RuntimeException("用户名为:" + username + "的用户余额不足"); } hql = "update Account a set a.balance = a.balance - ? where a.username=?"; getSession().createQuery(hql).setParameter(0, price).setParameter(1, username).executeUpdate(); } ``` 下面是spring的配置文件中已经设置了使用utf-8 ``` <!-- 配置hibernate sessionFactory的实例 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 配置数据源属性 --> <property name="dataSource" ref="dataSource"></property> <!-- 配置hibernate的配置文件路径及名称 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 配置hibernate 映射文件的位置及名称 --> <property name="mappingLocations" value="classpath:com/atguigu/spring/hibernate/entity/*.hbm.xml"></property> <property name="hibernateProperties"> <props> <prop key="connection.useUnicode">true</prop> <prop key="connection.characterEncoding">UTF-8</prop> </props> </property> </bean> ```

Myeclipse生成的session是否需要手动关闭?

看了几篇关于session关闭的文章,还是不能确定,初学hibernate3 不知道session是否需要手动关闭,没有用spring和其它的托管,web应用程序中 myeclipse生成的dao中的方法如下: 不知道是否需要在save方法里或查询的方法里加上 finally{ HibernateSessionFactory.closeSession(); } 如果不需要关闭的话,具体原因是什么呢? public void save(Custinfo transientInstance) { log.debug("saving WxGzjg instance"); try { Transaction tran = null; tran = (Transaction) getSession().beginTransaction(); getSession().save(transientInstance); log.debug("save successful"); tran.commit(); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } 我用myeclipse6.5,hibernate3.0生成的SessionFactory 类如下: package com.soft.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; private static final Log log = LogFactory.getLog(HibernateSessionFactory.class); static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { log.info("Error Creating SessionFactory"); System.err.println("Error Creating SessionFactory"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { log.info("Error Creating SessionFactory"); System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }

springmvc sessionFactory is null

严重: Servlet.service() for servlet [spring2] in context with path [/Lbl] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException 说明:@resource和@annotional都不起作用。 网上的方法都试过了,不起作用 spring2-servlet.xml <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.lbl.active" /> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean id="bookXmlView" class="org.springframework.web.servlet.view.xml.MarshallingView"> <constructor-arg> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"> <property name="autodetectAnnotations" value="true"/> </bean> </constructor-arg> </bean> <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> </bean> </beans> application.xml <context:annotation-config/> <!-- 自动扫描与装配 --> <context:component-scan base-package="com.lbl"></context:component-scan> <!-- 导入外部的properties--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 配置数据库路径 classpath:WEB-INF\classes\hibernate.cfg.xml--> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 配置数据库c3p0连接池 dataSource写错导致bean创建异常错误信息属性值设置错误 --> <property name="dataSource" > <!-- dataSouce应该写成dataSource第三个错误 --> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置数据库信息 --> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <!-- 其他配置 --> </bean> </property> </bean> <!-- 配置声明事物管理 采用注解方式--> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager"/> </beans> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Lbl</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring2</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring2</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 出错的类 @Transactional public class DaoService<T> implements DaoLbl<T>{ @Resource private SessionFactory sessionFactory; private Class<T> clazz; @SuppressWarnings("unchecked") public DaoService(){ System.out.println("---1---->>>:"+this.getClass()); // System.out.println("----2--->>>:"+this.getClass().getGenericSuperclass()); //使用反射技术获得 T的真实类型 ParameterizedType pt=(ParameterizedType)this.getClass()// .getGenericSuperclass();//获取当前new的泛型父类类型 System.out.println("------->:"); this.clazz=(Class<T>)pt.getActualTypeArguments()[0]; //获取第一个参数的实际类型 System.out.println("class--->" + clazz); } protected Session getSession(){ // // String path="C:/Users/admin/workspace/Lbl/WebContent/WEB-INF/applicationContext.xml"; // ApplicationContext ac=new FileSystemXmlApplicationContext(path); // SessionFactory sessionFactory=(SessionFactory)ac.getBean("sessionFactory"); // System.out.println("00001113333333----000->"+ sessionFactory); // System.out.println("00001113333333----000->"+ sessionFactory.openSession()); // return sessionFactory.openSession(); // System.out.println("0000000->"+ sessionFactory.getCurrentSession()); try { return sessionFactory.getCurrentSession(); } catch (Exception e) { e.getStackTrace(); } return null; } }

spring 和 hibernate继承事物之后,如何在代码中进行手动回滚?

1这是spring的事物配置内容,如何在代码中进行手动回滚,如同使用jdbc的时候,进行的事物回滚 <?xml version="1.0" encoding="UTF-8"?> 2 <beans 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:aop="http://www.springframework.org/schema/aop" 8 xmlns:tx="http://www.springframework.org/schema/tx" 9 xmlns:jpa="http://www.springframework.org/schema/data/jpa" 10 xmlns:cache="http://www.springframework.org/schema/cache" 11 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 12 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 13 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 14 http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd 15 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 16 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> 17 18 <context:component-scan base-package="dao"/> 19 <context:component-scan base-package="service"/> 20 <context:component-scan base-package="test"/> 21 22 <context:property-placeholder location="classpath:dbcp.properties"/> 23 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 24 <property name="driverClassName" value="${driverClassName}" /> 25 <property name="url" value="${url}" /> 26 <property name="username" value="${mysqlusername}" /> 27 <property name="password" value="${mysqlpassword}" /> 28 <property name="maxActive" value="${maxActive}" /> 29 <property name="maxIdle" value="${maxIdle}" /> 30 <property name="minIdle" value="${minIdle}" /> 31 <property name="maxWait" value="${maxWait}" /> 32 <property name="initialSize" value="${initialSize}" /> 33 <property name="logAbandoned" value="${logAbandoned}" /> 34 <property name="removeAbandoned" value="${removeAbandoned}" /> 35 <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> 36 <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" /> 37 <property name="numTestsPerEvictionRun" value="${numTestsPerEvictionRun}" /> 38 </bean> 39 40 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 41 <property name="dataSource" ref="dataSource" /> 42 43 <property name="hibernateProperties"> 44 <props> 45 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 46 <prop key="hibernate.show_sql">true</prop> 47 <prop key="current_session_context_class">thread</prop> 48 </props> 49 </property> 50 51 <property name="packagesToScan"> 52 <list> 53 <value>po</value> 54 </list> 55 </property> 56 </bean> 57 58 59 <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到--> 60 <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 61 <property name="sessionFactory" ref="sessionFactory"></property> 62 </bean> 63 64 <tx:advice id="txAdvice" transaction-manager="txManager"> 65 <tx:attributes> 66 <tx:method name="find*" propagation="REQUIRED" /> 67 <tx:method name="*" read-only="true"/> 68 </tx:attributes> 69 </tx:advice> 70 71 <aop:config proxy-target-class="true"> 72 <!-- <aop:advisor advice-ref="txAdvice" pointcut="execution(* dao.*.*(..))"/> --> 73 <aop:pointcut expression="execution(* dao.*.*(..))" id="pointcut"/> 74 <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> 75 </aop:config> 76 77 </beans> 这是jdbc的事物回滚的代码 public static void save(String name,int age) { Connection conn=null; PreparedStatement ps=null; try { conn=DBUtils.getConnection(); //把自动提交事务改为false conn.setAutoCommit(false); ps=conn.prepareStatement("insert into student(sname,age) value(?,?)"); ps.setString(1,name); ps.setInt(2, age); ps.executeUpdate(); //提交事务 conn.commit(); }catch(Exception e){ e.printStackTrace(); }finally{ JDBCUtils.close(null, ps, conn); } } public static void add(String name,int age) { Connection conn=null; PreparedStatement ps=null; try { conn=JDBCUtils.getConnection(); ps=conn.prepareStatement("insert into student(sname,age) value(?,?)"); for(int i=101;i<201;i++) { ps.setString(1,name+i); ps.setInt(2, age); ps.addBatch(); } ps.executeBatch(); }catch(Exception e){ e.printStackTrace(); }finally{ DBUtils.close(null, ps, conn); } } 使用上面的spring配置,如何才能在代码中如同jdbc一样进行try{}catch{}的手动的事物回滚。请大神知道一下,最好贴一下代码。

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

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

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

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

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

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

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Linux 会成为主流桌面操作系统吗?

整理 |屠敏出品 | CSDN(ID:CSDNnews)2020 年 1 月 14 日,微软正式停止了 Windows 7 系统的扩展支持,这意味着服役十年的 Windows 7,属于...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

学习总结之HTML5剑指前端(建议收藏,图文并茂)

前言学习《HTML5与CSS3权威指南》这本书很不错,学完之后我颇有感触,觉得web的世界开明了许多。这本书是需要有一定基础的web前端开发工程师。这本书主要学习HTML5和css3,看...

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

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

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

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

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

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

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

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

记一次腾讯面试,我挂在了最熟悉不过的队列上……

腾讯后台面试,面试官问:如何自己实现队列?

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

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

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

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

冒泡排序动画(基于python pygame实现)

本项目效果初始截图如下 动画见本人b站投稿:https://www.bilibili.com/video/av95491382 本项目对应github地址:https://github.com/BigShuang python版本:3.6,pygame版本:1.9.3。(python版本一致应该就没什么问题) 样例gif如下 ======================= 大爽歌作,mad

Redis核心原理与应用实践

Redis核心原理与应用实践 在很多场景下都会使用Redis,但是到了深层次的时候就了解的不是那么深刻,以至于在面试的时候经常会遇到卡壳的现象,学习知识要做到系统和深入,不要把Redis想象的过于复杂,和Mysql一样,是个读取数据的软件。 有一个理解是Redis是key value缓存服务器,更多的优点在于对value的操作更加丰富。 安装 yum install redis #yum安装 b...

现代的 “Hello, World”,可不仅仅是几行代码而已

作者 |Charles R. Martin译者 | 弯月,责编 | 夕颜头图 |付费下载自视觉中国出品 | CSDN(ID:CSDNnews)新手...

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

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

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

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

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

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

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

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

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

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

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

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

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

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

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

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

立即提问
相关内容推荐