小试ssh

2 篇文章 0 订阅
1 篇文章 0 订阅

小试ssh

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wanmait</groupId>
  <artifactId>hospitalHiber</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>hospitalHiber Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--命名一个,方便导入,控制整体版本-->
    <spring.version>5.1.8 RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
      <scope>runtime</scope>
    </dependency>
    <!--命名导入版本-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.17</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.12</version>
    </dependency>
    <dependency>
      <groupId>com.gitee.qdbp.thirdparty</groupId>
      <artifactId>ueditor</artifactId>
      <version>1.4.3.3</version>
    </dependency>
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20180813</version>
    </dependency>
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>2.10.6</version>
    </dependency>
    <!--hibernate所需的依赖-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.3.Final</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>hospitalHiber</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

spring.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:dbconfig.properties"/>
    <!--配置数据源 数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxWait" value="${maxWait}"/>
        <property name="filters" value="${filters}"/>
    </bean>

    <!--SessionFactory-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/hospital</prop>
                <prop key="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</prop>
            </props>
        </property>
        <property name="mappingLocations">
            <list>
                <value>classpath:mapping/*.hbm.xml</value>
            </list>
        </property>
    </bean>

    <!--事务管理器及注解驱动-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--包的扫描-->
    <context:component-scan base-package="com.wanmait.ssh.service"/>
    <context:component-scan base-package="com.wanmait.ssh.dao"/>

</beans>

点击右上角的 project structrue
与数据库相连
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Department.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.wanmait.ssh.pojo.Department" table="department" schema="hospital">
        <!--主键自动生成不了,自己加-->
        <id name="id" column="id">
            <generator class="identity"/>
        </id>

        <property name="title" column="title"/>
        <!--默认值列加上insert=false属性-->
        <property name="doctorCount" column="doctor_count" insert="false"/>
        <property name="visible" column="visible" insert="false"/>


        <!--inverse为true,表示让对方(Doctor)来管理关系, false 我方来管理关系。 在一对多配置时都配置为true 在多对多时需要考虑业务-->
        <!--cascade级联操作,cascade:级联操作,比如删除了骨科department,则会删除骨科下的所有doctor
                                     none: 不进行级联操作
                                     delete:级联删除
                                     save-update: 级联保存和级联更新
                                     all:所有情况都进行级联操作
                                     ....-->
        <set name="doctors" inverse="true" cascade="delete">
            <key>
                <!--注意一下not-null=true属性-->
                <column name="department_id" not-null="true"/>
            </key>
            <one-to-many not-found="ignore" class="com.wanmait.ssh.pojo.Doctor"/>
        </set>
    </class>
</hibernate-mapping>

Doctor.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.wanmait.ssh.pojo.Doctor" table="doctor" schema="hospital">
        <!--主键-->
        <id name="id" column="id">
            <generator class="identity"/>
        </id>
        <property name="name" column="name"/>
        <property name="scope" column="scope"/>
        <property name="info" column="info"/>
        <property name="visible" column="visible"/>
        <!--多对一-->
        <many-to-one name="department" class="com.wanmait.ssh.pojo.Department">
            <column name="department_id" not-null="true"/>
        </many-to-one>
    </class>
</hibernate-mapping>

DepartmentDAOImpl

package com.wanmait.ssh.dao.impl;

import com.wanmait.ssh.dao.DepartmentDAO;
import com.wanmait.ssh.pojo.Department;
import com.wanmait.ssh.pojo.Doctor;
import com.wanmait.ssh.service.DepartmentService;
import com.wanmait.ssh.util.Pager;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/*让spring管理*/
@Repository
public class DepartmentDAOImpl implements DepartmentDAO {

    /*注入session工厂*/
    @Resource
    private SessionFactory sessionFactory;
    public Session getSession()
    {
        return this.sessionFactory.getCurrentSession();
    }


    /*插入一条新数据*/
    @Override
    public void insert(Department object) {
        //临时对象
        this.getSession().save(object);//持久化对象 持久化对象在事务结束时会和数据库进行同步
        object.setTitle("喉科");
        //this.getSession().update(object);  //更新
        //事务结束session关闭  对象变为脱管对象


        /*婚姻的三种状态:未婚 已婚 离异

        对象的三种状态:
        临时对象/瞬时对象: 	对象和session没有任何关系,未经session操作
        持久对象、持久化对象:
        持久化对象在事务结束时会和数据库进行同步
        经过session进行save update get .....
        脱管对象、离线对象:
        session关闭之后*/
    }

    /*更新*/
    @Override
    public void update(Department object) {
        this.getSession().update(object);
    }

    /*假删除*/
    @Override
    public void delete(Integer id) {
        String hql = "update Department set visible=false where id=:id";
        this.getSession().createQuery(hql).setParameter("id",id).executeUpdate();

    /*        Query query = this.getSession().createQuery(hql);
        query.setParameter("id",id);
        query.executeUpdate();*/

        /*真删*/
        /*this.getSession().delete(questionType);*/
    }

    @Override
    public void delete(String ids) {

    }


    /*根据Id查询单条数据*/
    @Override
    public Department findById(Integer id) {
       /* String hql = "from Department dp left join fetch dp.doctors where dp.id=:id";
        Query<Department>query = this.getSession().createQuery(hql,Department.class);
        query.setParameter("id",id);
        return query.uniqueResult();*/

        /*return (Department) this.getSession().get("com.wanmait.ssh.pojo.Department",id);*/

/*============================================================================*/
           /*Department department = this.getSession().load(Department.class,id);
            Hibernate.initialize(department.getDoctors());
            return department;*/
/*============================================================================*/
        /*load 延迟查询,懒加载,用到的时候再发送sql语句取查询
                先把id给一个代理对象
        如果查询时session已经关闭,会报异常:
        org.hibernate.LazyInitializationException: could not initialize proxy  - no Session
        如果给定的id查询不到对象,报异常:
        org.hibernate.ObjectNotFoundException: No row with the given identifier exists*/
/*============================================================================*/
       /*使用Hibernate.intialize()初始化
            findById: Hibernate.initialize(question.getQuestionType());
            findAll:
            questions =  query.list();
            for (Question question : questions) {
                Hibernate.initialize(question.get    QuestionType());
            }*/
/*============================================================================*/
        /*设置lazy=false
            <many-to-one name="questionType" lazy="false" class="com.wanmait.demo.pojo.QuestionType">
                <column name="questionTypeId" not-null="true"/>
            </many-to-one>
        findById: 发送2条sql语句,一条sql语句查询question,一条sql语句查询questionType
        findAll:如果有n条数据,那么发送1+m(m<=n)条sql语句

        不建议使用,不管什么情况,只要查询question就会同时把questionType查询出来*/
/*============================================================================*/

        return this.getSession().get(Department.class,id);
    }


    /*默认查全部且去重复*/
    @Override
    public List<Department> findAll() {
        List<Department>departments = null;
        /*distinct 去重复*/
        String hql = "select distinct dp from Department dp left join fetch dp.doctors where dp.visible=true";
        Query query = this.getSession().createQuery(hql,Department.class);
        departments = query.list();

        return departments;
    }

    @Override
    public List<Department> findAll(Department object) {
        return null;
    }

    @Override
    public List<Department> findAll(Pager pager) {
        return null;
    }

    @Override
    public List<Department> findAll(Pager pager, Department object) {
        return null;
    }

    /*查询数据总数*/
    @Override
    public int getDataCount() {
        int count = 0;
        String hql = "select count(*) from Department where visible=true";
        count = (this.getSession().createQuery(hql,Long.class).uniqueResult()).intValue();

        return count;
    }

    @Override
    public int getDataCount(Department object) {
        return 0;
    }
}

测试类

package com.wanmait.ssh.service.impl.test;

import com.wanmait.ssh.dao.DepartmentDAO;
import com.wanmait.ssh.pojo.Department;
import com.wanmait.ssh.service.DepartmentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DepartmentServiceImplTest {
    @Resource
    private DepartmentService departmentService;

    /*默认查全部且去重复*/
    @Test
    public void testFindAll()
    {
        List<Department>departments = departmentService.findAll();
        departments.forEach(department -> System.out.println(department.getTitle()));
    }

    /*根据Id查询单条数据*/
    @Test
    public void testFindById()
    {
        Department department = departmentService.findById(1);
        System.out.println(department.getTitle());
    }

    /*查询数据总数*/
    @Test
    public void testGetCount()
    {
        System.out.println(departmentService.getDataCount());
    }

    /*新增一条数据*/
    @Test
    public void testInsert()
    {
        Department department = new Department();
        department.setDoctorCount(23);
        department.setTitle("疯牛病");

        departmentService.insert(department);
    }

    /*假删除*/
    @Test
    public void testDelete()
    {
        departmentService.delete(1);
    }
}

DoctorDAOImpl

package com.wanmait.ssh.dao.impl;

import com.wanmait.ssh.dao.DoctorDAO;
import com.wanmait.ssh.pojo.Doctor;
import com.wanmait.ssh.util.Pager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/*让spring管理*/
@Repository
public class DoctorDAOImpl implements DoctorDAO {

    /*注入session工厂*/
    @Resource
    private SessionFactory sessionFactory;
    public Session getSession()
    {
        return this.sessionFactory.getCurrentSession();
    }


    @Override
    public void insert(Doctor object) {

    }

    @Override
    public void update(Doctor object) {

    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void delete(String ids) {

    }


    /*根据Id查询单条数据*/
    @Override
    public Doctor findById(Integer id) {
        return this.getSession().createQuery("from Doctor d left join fetch d.department where d.id=:id",Doctor.class).setParameter("id",id).uniqueResult();
    }

    /*默认查全部*/
    @Override
    public List<Doctor> findAll() {
        List<Doctor>doctors = null;
        String hql = "from Doctor d left join fetch d.department dp where d.visible=true and dp.visible=true order by d.id desc";
        Query query = this.getSession().createQuery(hql,Doctor.class);
        doctors = query.list();

        return doctors;
    }

    @Override
    public List<Doctor> findAll(Doctor object) {
        return null;
    }

    @Override
    public List<Doctor> findAll(Pager pager) {
        return null;
    }

    @Override
    public List<Doctor> findAll(Pager pager, Doctor object) {
        return null;
    }

    @Override
    public int getDataCount() {
        return 0;
    }

    @Override
    public int getDataCount(Doctor object) {
        return 0;
    }


    /*根据关联表的Id查询数据*/
    @Override
    public List<Doctor> findAllById(Integer departmentId) {
        return this.getSession().createQuery("from Doctor d where department.id=:departmentId and d.visible=true",Doctor.class).setParameter("departmentId",departmentId).list();
    }
}

测试类

package com.wanmait.ssh.service.impl.test;

import com.wanmait.ssh.pojo.Doctor;
import com.wanmait.ssh.service.DoctorService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DoctorServiceImplTest {

    @Resource
    private DoctorService doctorService;

    /*默认查全部*/
    @Test
    public void testFindAll()
    {
        List<Doctor>doctors = doctorService.findAll();
        doctors.forEach(doctor -> System.out.println(doctor.getName()));
    }


    /*根据Id查询单条数据*/
    @Test
    public void testFindById()
    {
        System.out.println(doctorService.findById(1).getDepartment().getTitle());
    }

    /*根据关联表Id查询数据*/
    @Test
    public void testFindAllById()
    {
       List<Doctor>doctors = doctorService.findAllById(2);
       doctors.forEach(doctor -> System.out.println(doctor.getName()));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值