SSH搭建

wuchangjian2021-11-05 09:27:53编程学习

Hibernate+Sping+SpringMVC

创建maven项目,选择webapp骨架

在这里插入图片描述

配置maven,tomcat

在这里插入图片描述

在这里插入图片描述

导入依赖


 <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.1.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.7</version>

      <exclusions>
        <exclusion>
          <artifactId>log4j</artifactId>
          <groupId>log4j</groupId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>3.1.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>3.1.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>3.1.1.RELEASE</version>
    </dependency>

      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
      </dependency>

    <!-- commons -->
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>commons-pool</groupId>
      <artifactId>commons-pool</artifactId>
      <version>1.5.6</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.8.3</version>
    </dependency>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>jsr250-api</artifactId>
      <version>1.0</version>
    </dependency>

    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- hibernate配置-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.8.Final</version>
    </dependency>


    <!-- mysql驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.29</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>

配置jdbc.properties

#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = root

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

配置log4j.properties

log4j.rootCategory=warn,logfile,stdout
#stdout configure
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %d %p [%c] - %m%n


#logfile configure
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=E:/IdeaProjects/sshexecise/xxgl.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern= %d %p [%c] - <%m>%n
log4j.logger.com.xysd=DEBUG

配置applicationContext.xml

<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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.xysd.ssh">
        <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <!--扫描配置文件(这里指向的是之前配置的那个config.properties)-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />  <!--数据库连接驱动-->
        <property name="url" value="${jdbc.url}" />     <!--数据库地址-->
        <property name="username" value="${jdbc.username}" />   <!--用户名-->
        <property name="password" value="${jdbc.password}" />   <!--密码-->
        <property name="maxIdle" value="40" />      <!--最大连接数-->
        <property name="minIdle" value="1" />       <!--最小连接数-->
        <property name="initialSize" value="10" />      <!--初始化连接池内的数据库连接-->
        <property name="maxActive" value="20" />  <!--最大空闲时间-->
    </bean>

    <!--配置session工厂-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.xysd.ssh.pojo" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>   <!--指定数据库方言-->
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>     <!--在控制台显示执行的数据库操作语句-->
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>     <!--在控制台显示执行的数据哭操作语句(格式)-->
            </props>
        </property>
    </bean>

    <!-- 事物管理器配置  -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

配置springMvc.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射-->
    <mvc:annotation-driven ></mvc:annotation-driven>
    <context:component-scan base-package="com.xysd.ssh.controller" />
    <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
    <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-INF/view/" />      <!-- 前缀 -->
        <property name="suffix" value=".jsp" />   <!-- 后缀 -->
    </bean>

</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>Archetype Created Web Application</display-name>

  <!-- 地址为http://localhost:8080/  显示的默认网页-->
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>

  <!--加载Spring的配置文件到上下文中去-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:applicationContext.xml
    </param-value>
  </context-param>

  <!-- spring MVC config start-->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!-- 此处指向的的是SpringMVC的配置文件 -->
      <param-value>classpath:springMvc.xml</param-value>
    </init-param>
    <!--配置容器在启动的时候就加载这个servlet并实例化-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- spring MVC config end-->


  <!-- Spring监听器 -->
  <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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

创建实体类,repository接口及实现类

@Entity
@Table(name = "cz_user")
public class Users {

    @Column(name = "user_id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer userId;
    @Column(name = "user_name")
    private String username;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Column(name = "reg_time")
    private Date regTime;


    //配置mappedBy属性的同时加上@JoinColumn会抛出异常
    //mappedBy 让多的一方去维护外键 在插入的时候会减少update操作
    @OneToMany(fetch = FetchType.LAZY,targetEntity = Address.class,mappedBy = "users")
    //@JoinColumn(name = "user_id")//外键维护
    private List<Address> addressList = new ArrayList<Address>();

    public List<Address> getAddressList() {
        return addressList;
    }

    public void setAddressList(List<Address> addressList) {
        this.addressList = addressList;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getRegTime() {
        return regTime;
    }

    public void setRegTime(Date regTime) {
        this.regTime = regTime;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", username='" + username + '\'' +
                ", email='" + email + '\'' +
                ", password='" + password + '\'' +
                ", regTime=" + regTime +
                ", addressList=" + addressList +
                '}';
    }
@Entity
@Table(name = "cz_address")
public class Address {

    @Column(name = "address_id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer addressId;
//    @Column(name = "user_id")
//    private Integer userId;
    @Column(name = "consignee")
    private String consignee;
    @Column(name = "province")
    private Integer province;
    @Column(name = "city")
    private Integer city;
    @Column(name = "district")
    private Integer district;
    @Column(name = "street")
    private String street;
    @Column(name = "zipcode")
    private String zipcode;
    @Column(name = "telphone")
    private String telphone;
    @Column(name = "mobile")
    private String mobile;


    @ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
//    @JoinColumn(name = "user_id")
    private Users users;

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

//    public Integer getUserId() {
//        return userId;
//    }
//
//    public void setUserId(Integer userId) {
//        this.userId = userId;
//    }

    public Integer getAddressId() {
        return addressId;
    }

    public void setAddressId(Integer addressId) {
        this.addressId = addressId;
    }


    public String getConsignee() {
        return consignee;
    }

    public void setConsignee(String consignee) {
        this.consignee = consignee;
    }

    public Integer getProvince() {
        return province;
    }

    public void setProvince(Integer province) {
        this.province = province;
    }

    public Integer getCity() {
        return city;
    }

    public void setCity(Integer city) {
        this.city = city;
    }

    public Integer getDistrict() {
        return district;
    }

    public void setDistrict(Integer district) {
        this.district = district;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    public String getTelphone() {
        return telphone;
    }

    public void setTelphone(String telphone) {
        this.telphone = telphone;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "Address{" +
                "addressId=" + addressId +
//                ", userId=" + userId +
                ", consignee='" + consignee + '\'' +
                ", province=" + province +
                ", city=" + city +
                ", district=" + district +
                ", street='" + street + '\'' +
                ", zipcode='" + zipcode + '\'' +
                ", telphone='" + telphone + '\'' +
                ", mobile='" + mobile + '\'' +
                '}';
    }
}


public interface UserAddressDao {

    public List<Users> getUserList(UserVO userVO);

    public int getCount(UserVO userVO);

    public List<Users> getPage(UserVO userVO);

    public int save(Users users);

    public int update(Users users);

    public int delete(int userId);

    /**
     * 根据用户id获取用户及住址信息
     * @param id
     * @return
     */

    public Users getUserByUserId(int id);

    public List<Users> get(UserVO userVO);

    public Address getAddress(int id);

    public List<Integer> getUserIds();

    public List<Users> getUsers();

    public void getCount();

    public List<Users> queryUsers();

    public void queryUsersIterator();

    public Users getSingleUsers();

    public int updateBingFa(Users users);
}
@Repository
public class UserAddressDaoImpl implements UserAddressDao {

    private static Logger logger = Logger.getLogger(UserAddressDaoImpl.class);

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }


    @Override
    public List<Users> getUserList(UserVO userVO) {

//        StringBuilder sb = new StringBuilder("select username,email,regTime from Users where 1=1 ");
//        if (StringUtils.isNotBlank(userVO.getUsername())) {
//            sb.append(" and username like %" + userVO.getUsername() + "%");
//        }
//        if (StringUtils.isNotBlank(userVO.getEmail())) {
//            sb.append(" and email like %" + userVO.getEmail() + "%");
//        }
//        List<Users> data = getCurrentSession().createQuery(sb.toString()).setFirstResult(1).setMaxResults(5).list();
        return getPage(userVO);
    }

    @Override
    public List<Users> getPage(UserVO userVO) {
        Map<String,Object> paramMap = new HashMap<>();
        StringBuilder sb = new StringBuilder("select username,email,regTime from Users where 1=1 ");
        if (StringUtils.isNotBlank(userVO.getUsername())) {
            sb.append(" and username like :username ");
            paramMap.put("username", "%" + userVO.getUsername() + "%");
        }
        if (StringUtils.isNotBlank(userVO.getEmail())) {
            sb.append(" and email like :email ");
            paramMap.put("email","%" + userVO.getEmail() + "%");
        }

        List<Users> data = getCurrentSession().createQuery(sb.toString()).setProperties(paramMap)
                .setFirstResult(userVO.getPageNum() - 1)
                .setMaxResults(userVO.getPageSize())
                .list();
        return data;
    }

    @Override
    public int getCount(UserVO userVO) {
        Map<String,Object> paramMap = new HashMap<>();
        StringBuilder sb = new StringBuilder("select count(*) as total from Users where 1=1 ");
        if (StringUtils.isNotBlank(userVO.getUsername())) {
            sb.append(" and username like :username");
            paramMap.put("username", "%" + userVO.getUsername() + "%");
        }
        if (StringUtils.isNotBlank(userVO.getEmail())) {
            sb.append(" and email like :email");
            paramMap.put("email","%" + userVO.getEmail() + "%");
        }
        List list = getCurrentSession().createQuery(sb.toString()).setProperties(paramMap).list();
        return list != null && list.size() > 0 ? Integer.parseInt(list.get(0) + "") : 0;
    }

    @Override
    public int save(Users users) {
//        StringBuilder sql = new StringBuilder("insert into Users(username,password,email,regTime)");
//        getCurrentSession().save(sql.toString(), users);
//        return 0;
        return getCurrentSession()
                .createSQLQuery("insert into cz_user(user_name,email,password,reg_time) value (?,?,?,?)")
                .setString(0,"yu")
                .setString(1,"yu@163.com")
                .setString(2,"888888")
                .setDate(3,new Date())
                .executeUpdate();
    }


    /**
     * 解决Hibernate4执行update操作,不更新数据的问题
     后台封装java对象,使用hibernate4再带的update,执行不更新数据,不报错。
     使用
     Session session = this.getSessionFactory().getCurrentSession();
     ession.update(“update Users set username =?, password =? where userId =?”,users);不好使
     * @param users
     * @return
     */
    @Override
    public int update(Users users) {
//        return getCurrentSession().createQuery("update Users set username =?, password =? where userId =?")
//        .setString(0,users.getUsername())
//        .setString(1,users.getPassword())
//        .setInteger(2,users.getUserId())
//        .executeUpdate();
        return getCurrentSession().createSQLQuery("update cz_user set user_name = ?, password = ? where user_id = ? ")
                .setString(0,"guo")
                .setString(1,"101010")
                .setInteger(2,9)
                .executeUpdate();

    }

    @Override
    public int delete(int userId) {
         return getCurrentSession().createQuery("delete from Users where userId = ? ")
                 .setInteger(0,userId)
                 .executeUpdate();
    }

    /**
     * 无论是否为级联查询 使用 createSQLQuery查询 必须查询所有字段
     *         如果不想查询所有字段,createQuery  这个表名和字段名分别要对应类名和属性名
     * @param id
     * @return
     */
    @Override
    public Users getUserByUserId(int id) {
        String sql = "select u.*,a.* " +
                " from cz_user as u inner join cz_address as a on u.user_id = a.user_id where u.user_id = ?";
        //String sql = "select u.user_name,u.email,a.telphone,a.province from cz_user as u,cz_address as a where u.user_id = a.user_id and u.user_id = ?";
        List<Users> data = getCurrentSession().createSQLQuery(sql).addEntity(Users.class).setInteger(0,id).list();
        return data != null && data.size() > 0 ? data.get(0) : null;
    }

    /**
     * 在一对多或者一对一的关系下,需要加上@JoinColumn来指定外键列,避免生成一张中间表。

     而且经试验,多的一方(Employee)里的department必须加上@JoinColumn,Department里不加不会影响表的结构,不知道会不会有其它影响;

     但是如果Employee属于多的一方,如果没有指定外键列,还是会自动生成一个department_id外键列。
     * @param userVO
     * @return
     */

    @Override
    public List<Users> get(UserVO userVO) {
        Map<String,Object> paramMap = new HashMap<String,Object>();
        StringBuilder sb = new StringBuilder("select * from cz_user as u where 1=1 ");
        if (StringUtils.isNotBlank(userVO.getUsername())){
            sb.append(" and u.user_name like :user_name ");
            paramMap.put("user_name","%" + userVO.getUsername() + "%");
        }
        if (StringUtils.isNotBlank(userVO.getEmail())){
            sb.append(" and u.email like ? ");
            paramMap.put("email","%" + userVO.getEmail() + "%");
        }


        return getCurrentSession().createSQLQuery(sb.toString()).addEntity(Users.class).setProperties(paramMap).list();
    }

    @Override
    public Address getAddress(int id) {
        List<Address> list = getCurrentSession().createSQLQuery("select u.*,a.* from cz_user as u,cz_address as a where address_id = ? and a.user_id = u.user_id ").addEntity(Address.class).setInteger(0, 1).list();
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<Integer> getUserIds() {
        List<Integer> ids = getCurrentSession()
                .createSQLQuery("select user_id from cz_user where user_id < ? limit ?,?")
                .addEntity(Integer.class)
                .setInteger(0,10)
                .setInteger(1,0)
                .setInteger(2,3)
                .list();

        return ids;
    }

    public List<Users> getUsers() {

        List<Users> ids = getCurrentSession()
                .createQuery("select userId from Users where userId < ? limit ?,? ")
                .setInteger(0,10)
                .setInteger(1,0)
                .setInteger(2,3)
                .list();
        return ids;
    }

    public void getCount(){
        Object o = getCurrentSession().createSQLQuery("select count(*) from cz_user").uniqueResult();
        Object o1 = getCurrentSession().createSQLQuery("select count(user_name) from cz_user ").uniqueResult();
        System.out.println("count : " + o + " , " + "countUsername : " + o1);
    }

    @Override
    public List<Users> queryUsers() {
        List<Users> list = getCurrentSession().createSQLQuery("select * from cz_user ").addEntity(Users.class).list();
        return list;
    }

    @Override
    public void queryUsersIterator() {
        Iterator<Users> iterate = getCurrentSession().createQuery("from Users ")
                .iterate();
        while (iterate.hasNext()){
            Users users = iterate.next();
            System.out.println(users);
        }
    }

    @Override
    public Users getSingleUsers(){
        Users users = (Users) getCurrentSession().createQuery(" from Users where userId = 3").uniqueResult();
        System.out.println(users);
        users = (Users) getCurrentSession().get(Users.class,3);
        logger.warn(users);
        return users;
    }

    @Override
    public int updateBingFa(Users users) {
        Session session = getCurrentSession();
        session.beginTransaction();
        session.createSQLQuery(" update cz_user set user_name = ?,password = ? where user_id = ? ")
                .setString(0,users.getUsername())
                .setString(1,users.getPassword())
                .setInteger(2,users.getUserId())
                .executeUpdate();
        session.getTransaction().commit();
        return 1;
    }

创建service接口及实现类,controller

public interface UserAddressService {

    public List<Users> getUserList(UserVO userVO);

    public List<Users> getPage(UserVO userVO);

    public int getCount(UserVO userVO);

    public int save(Users users);

    public int update(Users users);

    public int delete(int userId);

    public Users getUsersByUserId(int id);

    public List<Users> get(UserVO userVO);
}
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    private UserAddressDao userAddressDao;

    @Override
    public List<Users> getUserList(UserVO userVO) {
        return userAddressDao.getUserList(userVO);
    }

    @Override
    public List<Users> getPage(UserVO userVO) {
        return userAddressDao.getPage(userVO);
    }

    @Override
    public int getCount(UserVO userVO) {
        return userAddressDao.getCount(userVO);
    }

    @Override
    public int save(Users users) {
        return userAddressDao.save(users);
    }

    @Override
    public int update(Users users) {
        return userAddressDao.update(users);
    }

    @Override
    public int delete(int userId) {
        return userAddressDao.delete(userId);
    }

    @Override
    public Users getUsersByUserId(int id) {
        return userAddressDao.getUserByUserId(id);
    }

    @Override
    public List<Users> get(UserVO userVO) {
        return userAddressDao.get(userVO);
    }
}
@Controller
@RequestMapping("/user/address")
public class UserAddressController {

    private static Logger logger = Logger.getLogger(UserAddressController.class);

    @Autowired
    private UserAddressService userAddressService;

    @RequestMapping(value = "/getUserList",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getUserList(String username,String email){
        UserVO userVO = new UserVO(username,email);
        List<Users> userList = userAddressService.getUserList(userVO);
        Map<String,Object> map = new HashMap<>();
        map.put("userList",userList);
        int count = userAddressService.getCount(userVO);
        map.put("total",count);
        logger.warn("total:" + count + " data size : " + userList.size());
        return JSON.toJSONString(map);
    }

    @RequestMapping(value = "/getPage",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getPage(@RequestParam(required = false) String username,
                          @RequestParam(required = false) String email,
                          @RequestParam(required = false,defaultValue = "1") int pageNum,
                          @RequestParam(required = false,defaultValue = "5") int pageSize){
        UserVO userVO = new UserVO(username,email,pageNum,pageSize);
        List<Users> userList = userAddressService.getUserList(userVO);
        Map<String,Object> map = new HashMap<>();
        map.put("userList",userList);
        int count = userAddressService.getCount(userVO);
        map.put("total",count);
        return JSON.toJSONString(map);
    }

    @RequestMapping("/save")
    @ResponseBody
    public String save(){
        Users users = new Users();
        users.setEmail("852@163.com");
        users.setPassword("777777");
        users.setUsername("dan");
        users.setRegTime(new Date());
        int save = userAddressService.save(users);
        return "success";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(){
        Users users = new Users();
        //users.setEmail("a18717931963@163.com");
        users.setPassword("222222");
        users.setUserId(1);
        users.setUsername("李金海");
        //users.setRegTime(new Date());
        int save = userAddressService.update(users);
        return "success";
    }


    @RequestMapping("/delete")
    @ResponseBody
    public String delete(){

        int save = userAddressService.delete(1);
        return "success";
    }
}

测试service接口

//指定在单元测试启动的时候创建spring的工厂类对象
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
//RunWith的value属性指定以spring test的SpringJUnit4ClassRunner作为启动类
//如果不指定启动类,默认启用的junit中的默认启动类
@RunWith(value = SpringJUnit4ClassRunner.class)
public class UserAddressServiceTest {

    public static Logger logger = Logger.getLogger(UserAddressServiceTest.class);

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    UserAddressDao userAddressDao;

    @Test
    public void test(){
        List<Users> usersList = userAddressService.getPage(new UserVO("h", null, 1, 2));
        logger.info(usersList.toString());
    }

    @Test
    public void test2(){
        Users usersByUserId = userAddressService.getUsersByUserId(3);
        System.out.println(usersByUserId);
    }

    @Test
    public void get(){
        List<Users> h = userAddressService.get(new UserVO("h", null));
        for (Users users : h) {
            System.out.println(users.toString());
        }
    }

    @Test
    public void insert(){
        int save = userAddressService.save(null);
        System.out.println(save);
    }

    @Test
    public void update(){
        int save = userAddressService.update(null);
        System.out.println(save);
    }

    @Test
    public void getAddressTest(){
        Address address = userAddressDao.getAddress(1);
        System.out.println(address.toString());
    }

    @Test
    public void getUserIdsTest(){
//        List<Integer> userIds = userAddressDao.getUserIds();
//        for (Integer userId : userIds) {
//            System.out.println(userId);
//        }
        List<Users> users = userAddressDao.getUsers();
        for (Users user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testCount(){
        userAddressDao.getCount();
    }

    @Test
    public void queryUsers(){
        List<Users> users = userAddressDao.queryUsers();
        System.out.println(users.toString());
    }

    @Test
    public void queryUsersIterator(){
         //userAddressDao.queryUsersIterator();
        Users singleUsers = userAddressDao.getSingleUsers();
        System.out.println(singleUsers);
    }

    @Test
    public void updateBingFaTest(){
        Users users = new Users();
        users.setUserId(3);
        users.setUsername("lizhihuan");
        users.setPassword("000000");
        userAddressDao.updateBingFa(users);
    }

仅供参考使用,项目搭建好之后,可以选择上面的一个方法进行测试,保证service接口测试成功,访问controller接口可以返回数据即可,其他自己根据需要自己编写测试

相关文章

颜色之ARGB与RGB、RGBA的区别与介绍

ARGB 是一种色彩模式,也就是RGB色彩模式附加上Alpha࿰...

​电缆浮球式液位开关​的原理

 电缆浮球式液位开关是利用塑胶射出一体成型,所以结构坚固,性...

面向对象的特征——多态

多态的含义,简单来说就是一类事物在不同时刻表现出不同的状态。 就...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。