SSH整合(註解方式)_jpa

1.導入jar包和配置

  • Jar包 導入 SSH整合jar包 + struts2-convention-plugin.jar (約定掃描)共38個
  • 配置文件

src下log4j.properties 日誌配置
src下創建db.properties文件,配置數據庫的連接

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url jdbc:mysql:///itcastspring
jdbc.username = root
jdbc.password = root
<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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!-- 引入外部屬性配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- c3p0連接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
</beans>

2.Hibernate 實體類 映射採用JPA的註解完成

在cn.itcast.ssh.domain包下創建Book.java對象,添加註解的方式,取代Book.hbm.xml文件

//po實體類
@Entity (name="book")
public class Book {
	@Id		
	@GeneratedValue(strategy=GenerationType.AUTO)//自動
	private Integer id;//oid
	private String name;
	private Double price;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
	}
	
}

遇到異常:
修改註解:將@Table註解去掉


3.spring整合hibernate配置sessionFactory

我們在Hibernate第四天中學習了JPA,使用了JPA後,我們通過EntityManager來操作數據庫

package cn.itcast.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.SynchronizationType;
/**
 * JPA的工具類:
 *    加載JPA的persistence.xml文件,用於生成工廠
 *    調用工廠中的方法,創建操作數據庫的對象,並返回
 *   
 * @author Administrator
 *
 */
public class JPAUtil {
   //JPA的實體管理器工廠(相當於Hibernate的SessionFactory)
   private static EntityManagerFactory factory ;
   //使用靜態代碼塊賦值
  static{
	  try{
		  factory = Persistence.createEntityManagerFactory("myPersistenceUnit");
	  }catch(Exception ex){
		  ex.printStackTrace();
	  }
  } 
  /**
   * 使用管理器工廠生產一個管理器對象(獲取一個新的實體管理對象)
   * @return
   */
  public static EntityManager getEntityManager(){
	  //相當於Hibernate中的openSession()
	  return factory.createEntityManager();
  }
}

其實我們同樣也可以使用sessionFactory

第一步:配置sessionFactory

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
			<!-- 數據源注入 -->
	<property name="dataSource" ref="dataSource" />
	
	<!-- 配置hibernate的相關屬性 -->
	<property name="hibernateProperties">
		<props>
		<!-- 設置方言 -->
			<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
			<!-- 設置打印sql語句 -->
			<prop key="hibernate.show_sql">true</prop>
			<!-- 格式化sql語句 -->
			<prop key="hibernate.format_sql">true</prop>
			<!-- 自動建表 -->
			<prop key="hibernate.hbm2ddl.auto">update</prop>
		</props>
	</property>
	
	<!-- 引入映射配置 -->	
	<property name="packagesToScan">
		<list>
			<value>cn.itcast.ssh.domain</value>
		</list>
	</property>
			
</bean>

第二步:在web.xml 註冊struts2 (Filter器) 和 spring (Listener器 )

<!-- struts2的前端控制器 -->
<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>
<!-- spring的核心監聽器:初始化spring容器 -->
<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>

第三步:測試,將項目部署到tomcat,刪除數據表,啓動項目如果能自動建表 ---- 整合成功 !


4.編寫Action、Service、Dao註解註冊

4.1 編寫BookDao

第一步:配置applicationContext.xml,配置組件掃描Bean,開啓註解功能

<!-- bean組件掃描配置,開啓註解功能,可以在類上使用@Repository,@Service,@Action,@Component -->
<context:component-scan base-package="cn.itcast.ssh"/>

新建包:cn.itcast.ssh.dao,用來編寫dao:
第二步:創建IBookDao接口

public interface IBookDao {

	//保存圖書
	public void save(Book book);
	//更新圖書(根據id)
	public void update(Book book);
	//刪除圖書(根據id)
	public void delete(Book book);
	
	//根據id查詢
	public Book findById(Integer id);
	
	//查詢所有
	public List<Book> findAll();
	
	//複雜條件條件
	//1.命名查詢:QBN
	public List<Book> findByNamedQuery(String queryName, Object... values);
	
	//2.離線條件查詢:QBC
	public List<Book> findByCriteria(DetachedCriteria criteria);
}

第三步:創建BookDaoImpl的實現類
使用HibernateTemplate 實現增刪改查,使用註解@Repository和@Autowired

//圖書的持久層
//HibernateDaoSupport用來簡化代碼,能提供HibernateTemplate,
@Repository("bookDao")
public class BookDaoImpl extends HibernateDaoSupport implements IBookDao {
	//注入sessionFactory:注意寫法,這樣纔可以使用hibernateTemplate
	@Autowired
	public void setSuperSessionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
	//保存圖書
	public void save(Book book){
		//注入sesson工廠,獲取session--不會寫了
		//因爲:spring提供了模版類,來整合Hibernate
		super.getHibernateTemplate().save(book);
	}
	//更新圖書(根據id)
	public void update(Book book){
		super.getHibernateTemplate().update(book);
	}
	//刪除圖書(根據id)
	public void delete(Book book){
		super.getHibernateTemplate().delete(book);
	}
	
	//根據id查詢
	public Book findById(Integer id){
		return super.getHibernateTemplate().get(Book.class, id);
	}
	
	//查詢所有
	public List<Book> findAll(){
		return super.getHibernateTemplate().loadAll(Book.class);
//			return super.getHibernateTemplate().find("from Book");//hql方式
	}
	
	//複雜條件條件
	//1.命名查詢:QBN
	public List<Book> findByNamedQuery(String queryName, Object... values){
		return super.getHibernateTemplate().findByNamedQuery(queryName, values);
	}
	
	//2.離線條件查詢:QBC
	public List<Book> findByCriteria(DetachedCriteria criteria){
		return super.getHibernateTemplate().findByCriteria(criteria);
	}

}

那麼如何注入SessionFactory呢?使用@Autowired

//注入sessionFactory:注意寫法,這樣纔可以使用hibernateTemplate
@Autowired
public void setSuperSessionFactory(SessionFactory sessionFactory){
	super.setSessionFactory(sessionFactory);
}

4.2 編寫BookService(業務層)

新建包cn.itcast.ssh.service:用來存放service
業務層代碼,將dao注入到service,可以使用@Autowired存放到屬性上

第一步:創建接口類IBookService.java

public interface IBookService {

	//保存圖書
	//方法名不能隨便寫,配置事務save*,事務才能可寫
	public void saveBook(Book book);
	
	//查詢:複雜條件查詢,根據書名模糊查詢,配置事務find*,表示查詢,事務只讀
	public List<Book> findBookListByNameLike(String name);
}

第二步:創建接口類的實現類BookServiceImpl實現接口類

//圖書業務層
@Service("bookService")
@Transactional(readOnly=true)//事務(類級別的事務,一般定義成只讀,方法級別的事務定義成可寫)
public class BookServiceImpl implements IBookService{
	//注入dao層
	@Autowired
	private IBookDao bookDao;

	//保存圖書
	@Transactional(readOnly=false)//事務(方法級別的事務,覆蓋類級別的事務)
	public void saveBook(Book book){
		//調用dao層
		bookDao.save(book);
	}
	
	//查詢:複雜條件查詢,根據書名模糊查詢
	public List<Book> findBookListByNameLike(String name){
		//1.qbn
//		return bookDao.findByNamedQuery("Book.findBookListByNameLike", "%"+name+"%");
		
		//2.qbc
		DetachedCriteria criteria =DetachedCriteria.forClass(Book.class);//root對象類型
		criteria.add(Restrictions.like("name",  "%"+name+"%"));
		return bookDao.findByCriteria(criteria);
	}

}

第三步:聲明式事務管理 ,在Service層完成,添加註解@Transactional
(1)在applicationContext.xml文件中配置事務控制的註解寫法

<!-- 平臺事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	<!-- 注入sessionFactory -->
	<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 聲明式事務(註解驅動) -->
<tx:annotation-driven transaction-manager="transactionManager"/>

(2)類上定義只讀,因爲一個類中查詢的方法比較多

@Transactional(readOnly=true)//事務(類級別的事務,一般定義成只讀,方法級別的事務定義成可寫)
public class BookServiceImpl implements IBookService{

}

(3)增刪改方法上定義可寫,可寫的操作需要將事務定義可寫

//保存圖書
@Transactional(readOnly=false)//事務(方法級別的事務,覆蓋類級別的事務)
public void saveBook(Book book){

}

第四步:使用SrpingTest.java進行測試:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringTest {

	//注入service
	@Autowired
	private IBookService bookService;
	
	@Test
	public void testSave(){
		//保存圖書
		Book book = new Book();
		//book.setId(id)
		book.setName("約會專家周星星");
		book.setPrice(998d);
		bookService.saveBook(book);
	}
	
	@Test
	public void testFind(){
		//查詢
		List<Book> list = bookService.findBookListByNameLike("會");
		System.out.println(list);
	}
}

4.3 編寫BookAction

在cn.itcast.ssh.web.action中創建BookAction類,註解完成Service注入Action

//圖書管理的表現層
@Controller("bookAction")
@Scope("prototype")//多例!!!!!
public class BookAction extends ActionSupport implements ModelDriven<Book>{
	//數據模型對象
	private Book book=new Book();
	
	public Book getModel() {
		return book;
	}
	
	//成員變量
	@Autowired
	private IBookService bookService;
	
	//業務方法:保存圖書
	public String add(){
		System.out.println(book);
		//調用業務層保存...
		bookService.saveBook(book);
		return NONE;
	}
	
}

4.4 使用struts2註解,頁面訪問Action

第一步:在WebRoot下新建:addbook.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加圖書</title>
</head>
<body>
	<h1>歡迎使用Xxx的圖書管理系統</h1>
	<s:form action="book_add" namespace="/" method="post">
		圖書的名稱:<s:textfield name="name"/><br/>
		圖書的價格:<s:textfield name="price"/><br/>
		<s:submit value="保存"/><s:reset value="重置"/>
	</s:form>
</body>
</html>

如果添加namespace:

<s:form action="book_add" namespace="/ann" method="post"><!--或者是action="/ann/book_add" namespace="/"-->
	圖書的名稱:<s:textfield name="name"/><br/>
	圖書的價格:<s:textfield name="price"/><br/>
	<s:submit value="保存"/><s:reset value="重置"/>
</s:form>

第二步:導入Struts2 註解開發,基於約定掃描 (導入 struts2-convention-plugin.jar ),從struts2的struts-2.3.15.3-all\struts-2.3.15.3\lib查找
在這裏插入圖片描述
找到struts-plugin.xml文件
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章