SpringMVC简单整合Hibernate

maven添加依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

spring配置文件

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>models</value>
            </list>
        </property>
    </bean>
其中hibernate.hbm2ddl.auto 为自动创建表选项

packagesToScan 为对象模型路径


controller

@Controller
@RequestMapping("/")
public class HelloController {

    @Autowired
    private UserServices userServices;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ModelAndView printWelcome(HttpServletRequest request) {
        S_User user = userServices.get("1");
        System.out.println(user.getUsername());
        return new ModelAndView("index");
    }
}

services

@Service
public class UserServices {
    public UserServices() {
    }
    @Autowired
    private SessionFactory sessionFactory;

    public S_User get(String id) {
        return (S_User) new HibernateTemplate(sessionFactory).find("from S_User where id =" + id).get(0);
    }
}


这其中用到了自动注入@Autowired

需要在spring中配置bean路径 

 <context:component-scan base-package="com.springapp.mvc"/>
 <context:component-scan base-package="services.*"/>

其中services.*表示services包下的其他包中java文件,其本身包下文件是扫描不到的,例如services.Test.java是无效的,自动注入会显示找不到此bean


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页