Springmvc 配置(spring+hibernate+springmvc)

Springmvc 配置(spring+hibernate+springmvc)

Create a new web project

import jar package


The above package plus all jar packages of spring

The directory structure is as follows:


build package

entity ,dao, manager,web,

Spring's configuration files are all placed in the config/spring directory, including database configuration. Here, hibernate.cfg.xml will no longer be used for configuration, but will be placed in

inside spring-common.xml.

The xml file we will configure is as follows:


Web.Xml configuration

  <!-- Configuration character set --> 

  <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> 

   

     <!-- Load all configuration files --> 

 <context-param> 

   <param-name>contextConfigLocation</param-name> 

   <param-value>classpath*:config/spring/spring-*.xml</param-value> 

 </context-param> 

   

 <!-- Configure Spring listener   -->

 <listener> 

   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 

 </listener> 

 

  <!-- Configure SpringMVC --> 

 <servlet> 

   <servlet-name>springMVC</servlet-name> 

   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 

   <init-param> 

        <param-name>contextConfigLocation</param-name> 

        <param-value>classpath*:config/spring/spring-mvc.xml</param-value> 

   </init-param> 

   <load-on-startup>1</load-on-startup> 

 </servlet> 

 <servlet-mapping> 

   <servlet-name>springMVC</servlet-name> 

   <url-pattern>/</url-pattern> 

  </servlet-mapping>    

 

spring-mvc.xml configuration

  <!-- Annotation scanning package --> 

   <context:component-scanbase-package="com"/> 

 

   <!-- Open annotations --> 

   <mvc:annotation-driven/> 

     

   <!-- Access to static resources ( js /image) --> 

   <mvc:resourceslocation="/js/"mapping="/js/**"/> 

    <mvc:resourceslocation="/image/"mapping="/image/**"/> 

   <!-- Define view resolver -->   

   <beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 

        <propertyname="prefix"value="/jsp/"></property> 

        <propertyname="suffix"value=".jsp"></property> 

</bean>

 

spring-common.xml configuration

<!-- Configure data source --> 

   <beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 

        <propertyname="driverClassName"value="org.gjt.mm.mysql.Driver"></property> 

        <propertyname="url"value="jdbc:mysql:///world"></property> 

        <propertyname="username"value="root"></property> 

        <propertyname="password"value="root"></property> 

   </bean> 

     

   <!-- deploy SessionFactory --> 

   <beanid="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 

        <propertyname="dataSource"ref="dataSource"/> 

        <propertyname="hibernateProperties"> 

            <props> 

                <propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 

                <propkey="hibernate.hbm2ddl.auto">update</prop> 

                <propkey="hibernate.show_sql">true</prop> 

                <propkey="hibernate.format_sql">true</prop> 

            </props> 

        </property> 

        <propertyname="annotatedClasses"> 

            <list> 

                <value>com.test.entity.Book</value> 

            </list> 

        </property> 

   </bean> 

     

   <!-- Configure a transaction manager --> 

   <beanid="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 

        <propertyname="sessionFactory"ref="sessionFactory"/> 

   </bean> 

     

   <!-- Configure the transaction, use the proxy method --> 

   <beanid="transactionProxy"class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"abstract="true">   

        <propertyname="transactionManager"ref="transactionManager"></property>   

        <propertyname="transactionAttributes">   

            <props>   

                <propkey="add*">PROPAGATION_REQUIRED,-Exception</prop>   

                <propkey="modify*">PROPAGATION_REQUIRED,-myException</prop>   

                <propkey="del*">PROPAGATION_REQUIRED</prop>   

                <propkey="*">PROPAGATION_REQUIRED</prop>   

            </props>   

        </property>   

    </bean>  

Background code:

Example: Basic operations of adding, deleting, modifying and checking Book


Book.java (entity class) (jpa automatically generates code, the primary key ID here uses uuid)

package com.test.entity;

 

 

import java.io.Serializable;

import javax.persistence.*;

 

importorg.hibernate.annotations.GenericGenerator;

 

 

/**

 *The persistent class for the book database table.

 *

 */

@Entity

@Table(name="book") 

public class Book implements Serializable {

         privatestatic final long serialVersionUID = 1L;

 

   @Id 

    @GeneratedValue(generator="system-uuid") 

   @GenericGenerator(name ="system-uuid",strategy="uuid") 

   @Column

         privateint id;

 

   @Column

   private String auther;

 

   @Column

   private String bookname;

 

   @Column

   private String isbn;

 

   @Column

   private int price;

 

   @Column

   private int stock;

 

         publicBook() {

         }

 

         public getId() {

                   returnthis.id;

         }

 

         publicvoid setId(int id) {

                   this.id= id;

         }

 

         publicString getAuther() {

                   returnthis.auther;

         }

 

         publicvoid setAuther(String auther) {

                   this.auther= auther;

         }

 

         publicString getBookname() {

                   returnthis.bookname;

         }

 

         publicvoid setBookname(String bookname) {

                   this.bookname= bookname;

         }

 

         publicString getIsbn() {

                   returnthis.isbn;

         }

 

         publicvoid setIsbn(String isbn) {

                   this.isbn= isbn;

         }

 

         publicint getPrice() {

                   returnthis.price;

         }

 

         publicvoid setPrice(int price) {

                   this.price= price;

         }

 

         publicint getStock() {

                   returnthis.stock;

         }

 

         publicvoid setStock(int stock) {

                   this.stock= stock;

         }

 

}

Service's code:

BookDao

package com.test.dao;

 

import java.util.List;

 

import com.test.entity.Book;

 

public interface BookDao {

        

   public Book getBook(String id); 

   

   public List<Book> getAllBook(); 

     

   public void addBook(Book book); 

     

   public boolean delBook(String id); 

     

public booleanupdateBook(Book book); 

 

 

}

BookDaoImpl

package com.test.dao;

 

import java.util.List;

 

import org.hibernate.Query;

import org.hibernate.SessionFactory;

 

import com.test.entity.Book;

 

public class BookDaoImpl implements BookDao {

   private SessionFactory sessionFactory; 

   

   public void setSessionFactory(SessionFactory sessionFactory) { 

       this.sessionFactory = sessionFactory; 

   } 

   @Override

   publicBook getBook(String id) {

      //TODO Auto-generated method stub

       String hql = "from book u where u.id=?";  

       Query query = sessionFactory.getCurrentSession().createQuery(hql); 

       query.setString(0, id); 

         

       return (Book)query.uniqueResult(); 

   }

 

   @Override

   publicList<Book> getAllBook() {

      //TODO Auto-generated method stub

        String hql = "from book"; 

       Query query = sessionFactory.getCurrentSession().createQuery(hql); 

         

       return query.list(); 

   }

 

   @Override

   publicvoid addBook(Book book) {

      //TODO Auto-generated method stub

      sessionFactory.getCurrentSession().save(book); 

   }

 

   @Override

   publicboolean delBook(String id) {

      //TODO Auto-generated method stub

       String hql = "delete book u where u.id = ?"; 

       Query query = sessionFactory.getCurrentSession().createQuery(hql); 

       query.setString(0, id); 

         

       return (query.executeUpdate() > 0); 

   }

 

   @Override

   publicboolean updateBook(Book book) {

      //TODO Auto-generated method stub

       String hql = "update book u set u.bookname = ?,u.isbn=?,u.price=?,u.stock=?where u.id = ?"; 

       Query query = sessionFactory.getCurrentSession().createQuery(hql); 

       query.setString(0, book.getAuther()); 

       query.setString(1, book.getBookname()); 

       query.setString(2, book.getIsbn()); 

        query.setInteger(3, book.getPrice());

       query.setInteger(4, book.getStock());

       return (query.executeUpdate() > 0); 

   }

 

}

BookManager

package com.test.manager;

 

import java.util.List;

 

import com.test.entity.Book;

 

 

public interface BookManager {

   public Book getBook(String id); 

   

   public List<Book> getAllBook(); 

     

   public void addBook(Book book); 

     

   public boolean delBookr(String id); 

     

   public boolean updateBook(Book book); 

}

BookManagerImpl

package com.test.manager;

 

import java.util.List;

 

import com.test.dao.BookDao;

import com.test.entity.Book;

 

public class BookManagerImpl implementsBookManager {

         privateBookDao bookDao;

        

         publicvoid setBookDao(BookDao bookDao) {

                   this.bookDao= bookDao;

         }

 

         @Override

         publicBook getBook(String id) {

                   //TODO Auto-generated method stub

                   returnbookDao.getBook(id);

         }

 

         @Override

         publicList<Book> getAllBook() {

                   //TODO Auto-generated method stub

                   returnbookDao.getAllBook();

         }

 

         @Override

         publicvoid addBook(Book book) {

                   //TODO Auto-generated method stub

                    bookDao.addBook(book);

         }

 

         @Override

         publicboolean delBookr(String id) {

                   //TODO Auto-generated method stub

                   returnbookDao.delBook(id);

         }

 

         @Override

         publicboolean updateBook(Book book) {

                   //TODO Auto-generated method stub

                   returnbookDao.updateBook(book);

         }

 

}

The code of the control:

After the controller is added:

The next step is to inject bookDao into


 

spring-beans.xml

 

<beanid="bookDao"class="com.test.dao.BookDaoImpl"> 

        <propertyname="sessionFactory"ref="sessionFactory"></property> 

   </bean> 

 

   <beanid="bookManagerBase"class="com.test.manager.BookManagerImpl"> 

        <propertyname="bookDao"ref="bookDao"></property> 

   </bean> 

     

   <!-- Here is the agent --> 

   <beanname="bookManager"parent="transactionProxy"> 

        <propertyname="target"ref="bookManagerBase"></property> 

    </bean>  

 If there is no error in the startup project, it means that there is no problem with the name configuration, database connection and bean injection, etc., and then you can test whether it is correct.

Guess you like

Origin blog.csdn.net/qi95719/article/details/53057184