全注解SSH
全注解SSH一,hibernate annotation
Class注解:
1. @Entity:表明當(dāng)前類是一個(gè)持久化類
2. @Table(name="team",catalog="NBA"):映射一個(gè)表team,所對應(yīng)的數(shù)據(jù)庫是NBA,可以省略
字段屬性注解:
1. @GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
解釋:表明該字段是主鍵,自增長,不為空而且是唯一的
2. @Column(name = "description", length = 500)
解釋:映射表中的description字段,長度是500
3. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
解釋:級聯(lián)操作:cascade = CascadeType.ALL,延遲加載:fetch = FetchType.LAZY,映射:mappedBy = "category",一對多方式
4. @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
解釋:延遲加載:多對一方式,關(guān)聯(lián)信息:外鍵name = "category_id"
OneToMany事例代碼:
數(shù)據(jù)庫:mysql
category表:id,name,description (<Pk>id)
product表:id,name,price,description,category_id
(<pk>id ,<fk>category_id)
Category.java
package com.b510.examples;
import java.util.HashSet;
import java.util.Set;
// 標(biāo)準(zhǔn)注解
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
//增加的注解
import org.hibernate.annotations.GenericGenerator;
//當(dāng)前的類是一個(gè)持久化類,是Category這個(gè)類。他映射了一個(gè)表category。所對應(yīng)的 數(shù)據(jù)庫是users
//這句:@Table(name = "category", catalog = "users") 可以省略
@Entity
@Table(name = "category", catalog = "users")
public class Category implements java.io.Serializable {
private static final long serialVersionUID = 3240281547213597385L;
private Integer id;
private String name;
private String description;
private Set<Product> products = new HashSet<Product>(0);
public Category() {
}
public Category(String name, String description, Set<Product> products) {
this.name = name;
this.description = description;
this.products = products;
}
// 主鍵 :@Id 主鍵生成方式:strategy = "increment"
//映射表中id這個(gè)字段,不能為空,并且是唯一的
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//映射表中name這個(gè)字段 ,長度是500
@Column(name = "name", length = 500)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//映射表中description這個(gè)字段 ,長度是500
@Column(name = "description", length = 500)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
//級聯(lián)操作:cascade = CascadeType.ALL
//延遲加載:fetch = FetchType.LAZY
//映射:mappedBy = "category"
//一對多方式
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
public Set<Product> getProducts() {
return this.products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
}
Product.java
代碼:
package com.b510.examples;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "product", catalog = "users")
public class Product implements java.io.Serializable {
private static final long serialVersionUID = -1546206493725028472L;
private Integer id;
private Category category;
private String name;
private String price;
private String descripton;
public Product() {
}
public Product(Category category, String name, String price,
String descripton) {
this.category = category;
this.name = name;
this.price = price;
this.descripton = descripton;
}
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//延遲加載:多對一方式
//關(guān)聯(lián)信息:外鍵name = "category_id"
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
public Category getCategory() {
return this.category;
}
public void setCategory(Category category) {
this.category = category;
}
@Column(name = "name", length = 500)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "price", length = 10)
public String getPrice() {
return this.price;
}
public void setPrice(String price) {
this.price = price;
}
@Column(name = "descripton", length = 500)
public String getDescripton() {
return this.descripton;
}
public void setDescripton(String descripton) {
this.descripton = descripton;
}
}
ManyToMany事例代碼:
你可以通過@ManyToMany注解可定義的多對多關(guān)聯(lián). 同時(shí),你也需要通過注解@JoinTable描述關(guān)聯(lián)表和關(guān)聯(lián)條件. 如果是雙向關(guān)聯(lián),其中一段必須定義為owner,另一端必須定義為inverse(在對關(guān)聯(lián)表進(jìn)行更新操作時(shí)這一端將被忽略):
@Entity
public class Employer implements Serializable {
@ManyToMany(
targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,
cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
@JoinTable(
name="EMPLOYER_EMPLOYEE",
joinColumns=@JoinColumn(name="EMPER_ID"),
inverseJoinColumns=@JoinColumn(name="EMPEE_ID")
)
public Collection getEmployees() {
return employees;
}
...
}
@Entity
public class Employee implements Serializable {
@ManyToMany(
cascade = {CascadeType.PERSIST, CascadeType.MERGE},
mappedBy = "employees",
targetEntity = Employer.class
)
public Collection getEmployers() {
return employers;
}
}
二,Spring注釋
@Component 注釋外,還定義了幾個(gè)擁有特殊語義的注釋,它們分別是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,這 3 個(gè)注釋和 @Component 是等效的,但是從注釋類的命名上,很容易看出這 3 個(gè)注釋分別和持久層、業(yè)務(wù)層和控制層(Web 層)相對應(yīng)。雖然目前這 3 個(gè)注釋和 @Component 相比沒有什么新意,但 Spring 將在以后的版本中為它們添加特殊的功能。所以,如果 Web 應(yīng)用程序采用了經(jīng)典的三層分層結(jié)構(gòu)的話,最好在持久層、業(yè)務(wù)層和控制層分別采用 @Repository、@Service 和 @Controller 對分層中的類進(jìn)行注釋,而用 @Component 對那些比較中立的類進(jìn)行注釋。
@Controller
例如
@Controller
public class SoftCreateController extends SimpleBaseController {}
或者
@Controller("softCreateController")
說明:@Controller 負(fù)責(zé)注冊一個(gè)bean 到spring 上下文中,bean 的ID 默認(rèn)為類名稱開頭字母小寫
@Service
例如
@Service
public class SoftCreateServiceImpl implements ISoftCreateService {}
或者
@Service("softCreateServiceImpl")
說明:@Service 負(fù)責(zé)注冊一個(gè)bean 到spring 上下文中,bean 的ID 默認(rèn)為類名稱開頭字母小寫
@Autowired
例如
@Autowired
private ISoftPMService softPMService;
或者
@Autowired(required=false)
private ISoftPMService softPMService = new SoftPMServiceImpl();
說明:
@Autowired 根據(jù)bean 類型從spring 上線文中進(jìn)行查找,注冊類型必須唯一,否則報(bào)異常。與@Resource 的區(qū)別在于,@Resource 允許通過bean 名稱或bean 類型兩種方式進(jìn)行查找@Autowired(required=false) 表示,如果spring 上下文中沒有找到該類型的bean 時(shí), 才會(huì)使用new SoftPMServiceImpl();
@RequestMapping
類
@Controller @RequestMapping("/bbtForum.do")
public class BbtForumController
{
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId,User user)
{}
}
方法
@RequestMapping("/softpg/downSoftPg.do")
@RequestMapping(value="/softpg/ajaxLoadSoftId.do",method= POST)
@RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)
說明:@RequestMapping 可以聲明到類或方法上
參數(shù)綁定說明如果我們使用以下的 URL 請求:
http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tomtopicId URL 參數(shù)將綁定到 topicId 入?yún)⑸希?userId 和 userName URL 參數(shù)將綁定到 user 對象的 userId 和 userName 屬性中。和 URL 請求中不允許沒有 topicId 參數(shù)不同,雖然 User 的 userId 屬性的類型是基本數(shù)據(jù)類型,但如果 URL 中不存在 userId 參數(shù),Spring 也不會(huì)報(bào)錯(cuò),此時(shí) user.userId 值為 0 。如果 User 對象擁有一個(gè) dept.deptId 的級聯(lián)屬性,那么它將和 dept.deptId URL 參數(shù)綁定。
@ModelAttribute
作用域:request
例如
@RequestMapping("/base/userManageCooper/init.do")
public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){}
或者
@ModelAttribute("coopMap")// 將coopMap 返回到頁 面
public Map<Long,CooperatorInfo> coopMapItems(){}
說明
@ModelAttribute 聲明在屬性上,表示該屬性的value 來源于model 里"queryBean" ,并被保存到model 里@ModelAttribute 聲明在方法上,表示該方法的返回值被保存到model 里
@Cacheable 和@CacheFlush
@Cacheable :聲明一個(gè)方法的返回值應(yīng)該被緩 存例如:@Cacheable(modelId = "testCaching")
@CacheFlush :聲明一個(gè)方法是清空緩存的觸發(fā)器例如:@CacheFlush(modelId = "testCaching")
@Resource
例如
@Resource
private DataSource dataSource; // inject the bean named 'dataSource'
或者
@Resource(name="dataSource")
@Resource(type=DataSource.class)
說明
@Resource 默認(rèn)按bean 的name 進(jìn)行查找,如果沒有找到會(huì)按type 進(jìn)行查找,此時(shí)與@Autowired 類 似
@PostConstruct 和@PreDestroy
@PostConstruct
在方法上加上注解@PostConstruct ,這個(gè)方法就會(huì)在Bean 初始化之后被Spring 容器執(zhí) 行(注:Bean 初始化包括,實(shí)例化Bean ,并裝配Bean 的屬性(依賴注入))。
@PreDestroy在方法上加上注解@PreDestroy ,這個(gè)方法就會(huì)在Bean 被銷毀前被Spring 容器執(zhí)行。
@Repository
與@Controller 、@Service 類似,都是向spring 上下文中注冊bean ,不在贅述。
@Component (不推薦使用)
@Component
@Component 是所有受Spring 管理組件的通用形式,Spring 還提供了更加細(xì)化的注解形式: @Repository 、@Service 、@Controller ,它們分別對應(yīng)存儲(chǔ)層Bean ,業(yè)務(wù)層Bean ,和展示層Bean 。
目前版本(2.5 )中,這些注解與@Component 的語義是一樣的,完全通用, 在Spring 以后的版本中可能會(huì)給它們追加更多的語義。 所以,我們推薦使用@Repository 、@Service 、@Controller 來替代@Component 。
@Scope
例如
@Scope("session")
@Repository()
public class UserSessionBean implementsSerializable {}
說明
在使用XML 定義Bean 時(shí),可以通過bean 的scope 屬性來定義一個(gè)Bean 的作用范圍,同樣可以通過@Scope 注解來完成
@SessionAttributes
說明
Spring 允許我們有選擇地指定 ModelMap 中的哪些屬性需要轉(zhuǎn)存到 session 中,以便下一個(gè)請求屬對應(yīng)的 ModelMap 的屬性列表中還能訪問到這些屬性。這一功能是通過類定義處標(biāo)注 @SessionAttributes 注解來實(shí)現(xiàn)的。@SessionAttributes 只能聲明在類上,而不能聲明在方法上。
例如
@SessionAttributes("currUser") // 將ModelMap 中屬性名為currUser 的屬性@SessionAttributes({"attr1","attr2"})
@SessionAttributes(types=User.class)
@SessionAttributes(types={User.class,Dept.class})
@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})
@InitBinder
說明
如果希望某個(gè)屬性編輯器僅作用于特定的 Controller ,可以在 Controller 中定義一個(gè)標(biāo)注 @InitBinder 注解的方法,可以在該方法中向 Controller 了注冊若干個(gè)屬性編輯器
例如
@InitBinderpublic
void initBinder(WebDataBinder binder)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class,
new CustomDateEditor(dateFormat, false));
}
posted on 2012-09-20 00:43 奮斗成就男人 閱讀(2607) 評論(0) 編輯 收藏 所屬分類: J2EE