全注解SSH

全注解SSH

一,hibernate annotation

Class注解:

1.       @Entity:表明当前类是一个持久化类

2.       @Table(name="team",catalog="NBA"):映射一个表team,所对应的数据库是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")

解释:级联操作:cascade =CascadeType.ALL,延迟加载:fetch =    FetchType.LAZY,映射:mappedBy ="category",一对多方式

4.       @ManyToOne(fetch = FetchType.LAZY)

@JoinColumn(name= "category_id")

解释:延迟加载:多对一方式,关联信息:外键name ="category_id"

OneToMany事例代码:

数据库: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;

// 标准注解

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;

//增加的注解

importorg.hibernate.annotations.GenericGenerator;

//当前的类是一个持久化类,是Category这个类。他映射了一个表category。所对应的数据库是users

//这句:@Table(name ="category", catalog = "users") 可以省略

@Entity

@Table(name = "category",catalog = "users")

public class Category implementsjava.io.Serializable {

 privatestatic final long serialVersionUID = 3240281547213597385L;

 privateInteger id;

 privateString name;

 privateString description;

 privateSet<Product> products = new HashSet<Product>(0);

 

 publicCategory() {

 }

 publicCategory(String name, String description, Set<Product> products) {

  this.name= name;

 this.description = description;

 this.products = products;

 }

 // 主键@Id   主键生成方式:strategy= "increment"

 //映射表中id这个字段,不能为空,并且是唯一的

 @GenericGenerator(name ="generator", strategy = "increment")

 @Id

 @GeneratedValue(generator ="generator")

 @Column(name = "id", unique = true,nullable = false)

 publicInteger getId() {

  returnthis.id;

 }

 publicvoid setId(Integer id) {

 this.id = id;

 }

 //映射表中name这个字段,长度是500

 @Column(name = "name", length = 500)

 publicString getName() {

  returnthis.name;

 }

 publicvoid setName(String name) {

 this.name = name;

 }

 

 //映射表中description这个字段,长度是500

 @Column(name = "description", length= 500)

 publicString getDescription() {

  returnthis.description;

 }

 publicvoid setDescription(String description) {

 this.description = description;

 }

 //级联操作:cascade= CascadeType.ALL

 //延迟加载:fetch =FetchType.LAZY

 //映射:mappedBy ="category"

 //一对多方式

 @OneToMany(cascade = CascadeType.ALL, fetch =FetchType.LAZY, mappedBy = "category")

 publicSet<Product> getProducts() {

  returnthis.products;

 }

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

importorg.hibernate.annotations.GenericGenerator;

 

@Entity

@Table(name = "product",catalog = "users")

public class Product implements java.io.Serializable{

 privatestatic final long serialVersionUID = -1546206493725028472L;

 privateInteger id;

 privateCategory category;

 privateString name;

 privateString price;

 privateString descripton;

 

 publicProduct() {

 }

 publicProduct(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)

 publicInteger getId() {

  returnthis.id;

 }

 publicvoid setId(Integer id) {

 this.id = id;

 }

 //延迟加载:多对一方式

 //关联信息:外键name ="category_id"

 @ManyToOne(fetch = FetchType.LAZY)

 @JoinColumn(name = "category_id")

 publicCategory getCategory() {

  returnthis.category;

 }

 publicvoid setCategory(Category category) {

 this.category = category;

 }

 @Column(name = "name", length = 500)

 publicString getName() {

  returnthis.name;

 }

 publicvoid setName(String name) {

 this.name = name;

 }

 @Column(name = "price", length = 10)

 publicString getPrice() {

  returnthis.price;

 }

 publicvoid setPrice(String price) {

 this.price = price;

 }

 @Column(name = "descripton", length= 500)

 publicString getDescripton() {

  returnthis.descripton;

 }

 publicvoid setDescripton(String descripton) {

 this.descripton = descripton;

 }

}

 

ManyToMany事例代码:

你可以通过@ManyToMany注解可定义的多对多关联. 同时,你也需要通过注解@JoinTable描述关联表和关联条件. 如果是双向关联,其中一段必须定义为owner,另一端必须定义为inverse(在对关联表进行更新操作时这一端将被忽略):

@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 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用@Repository@Service @Controller 对分层中的类进行注释,而用@Component 对那些比较中立的类进行注释。

 

@Controller

例如

@Controller             

public class SoftCreateController extendsSimpleBaseController {}

或者                            

@Controller("softCreateController")

说明:@Controller 负责注册一个bean spring 上下文中,bean ID 默认为类名称开头字母小写

 

@Service

例如

@Service             

public class SoftCreateServiceImpl implementsISoftCreateService {}

或者             

@Service("softCreateServiceImpl")

       说明:@Service 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写

 

@Autowired

例如

       @Autowired             

        private ISoftPMService softPMService;

         或者

         @Autowired(required=false)    

private ISoftPMService softPMService = newSoftPMServiceImpl();

说明:

    @Autowired 根据bean 类型从spring 上下文中进行查找,注册类型必须唯一,否则报异常。与@Resource 的区别在于,@Resource 允许通过bean 名称或bean 类型两种方式进行查找@Autowired(required=false) 表示,如果spring 上下文中没有找到该类型的bean 时, 才会使用newSoftPMServiceImpl();

 

 

@RequestMapping

 

         @Controller @RequestMapping("/bbtForum.do")

public class BbtForumController

       @RequestMapping(params= "method=listBoardTopic")

                   publicString 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 可以声明到类或方法上

 参数绑定说明如果我们使用以下的 URL 请求:

http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tomtopicIdURL 参数将绑定到 topicId 入参上,而 userId  userNameURL 参数将绑定到 user 对象的 userId  userName 属性中。和 URL 请求中不允许没有 topicId 参数不同,虽然 User  userId 属性的类型是基本数据类型,但如果 URL 中不存在 userId 参数,Spring 也不会报错,此时 user.userId 值为 0 。如果 User 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptIdURL 参数绑定。[z1] 

 

 

@ModelAttribute

作用域:request

例如            

@RequestMapping("/base/userManageCooper/init.do")

         publicString handleInit(@ModelAttribute("queryBean") ManagedUsersUser,Model model,){}

 或者

@ModelAttribute("coopMap")// 将coopMap 返回到页 面          

         publicMap<Long,CooperatorInfo>coopMapItems(){}              

说明

@ModelAttribute 声明在属性上,表示该属性的value 来源于model 里"queryBean" ,并被保存到model 里@ModelAttribute 声明在方法上,表示该方法的返回值被保存到model 里

 

 

@Cacheable 和@CacheFlush

@Cacheable :声明一个方法的返回值应该被缓 存例如:@Cacheable(modelId= "testCaching")

         @CacheFlush :声明一个方法是清空缓存的触发器例如:@CacheFlush(modelId= "testCaching")

 

@Resource

例如

         @Resource            

private DataSource dataSource; // inject thebean named 'dataSource'

 或者

@Resource(name="dataSource")

@Resource(type=DataSource.class)

 

说明

@Resource 默认按bean 的name 进行查找,如果没有找到会按type 进行查找,此时与@Autowired 类 似

@PostConstruct 和@PreDestroy

@PostConstruct

在方法上加上注解@PostConstruct ,这个方法就会在Bean 初始化之后被Spring 容器执 行(注:Bean 初始化包括,实例化Bean ,并装配Bean 的属性(依赖注入))。

@PreDestroy在方法上加上注解@PreDestroy ,这个方法就会在Bean 被销毁前被Spring 容器执行。

 

 

@Repository

 与@Controller 、@Service 类似,都是向spring 上下文中注册bean ,不在赘述。

 

 

@Component (不推荐使用)

@Component

@Component 是所有受Spring 管理组件的通用形式,Spring 还提供了更加细化的注解形式: @Repository 、@Service 、@Controller ,它们分别对应存储层Bean ,业务层Bean ,和展示层Bean 。

目前版本(2.5 )中,这些注解与@Component 的语义是一样的,完全通用, 在Spring 以后的版本中可能会给它们追加更多的语义。 所以,我们推荐使用@Repository 、@Service 、@Controller 来替代@Component 。

 

 

@Scope

例如

          @Scope("session")

              @Repository()

               publicclass UserSessionBean implementsSerializable {}

 说明

 

在使用XML 定义Bean 时,可以通过bean 的scope 属性来定义一个Bean 的作用范围,同样可以通过@Scope 注解来完成

 

 

@SessionAttributes

说明

Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。@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

说明

如果希望某个属性编辑器仅作用于特定的 Controller ,可以在 Controller 中定义一个标注 @InitBinder 注解的方法,可以在该方法中向 Controller 了注册若干个属性编辑器

 

 例如

@InitBinderpublic

void initBinder(WebDataBinder binder)

{

  SimpleDateFormat dateFormat = newSimpleDateFormat("yyyy-MM-dd");

  dateFormat.setLenient(false);

  binder.registerCustomEditor(Date.class,

         new CustomDateEditor(dateFormat, false));

}


??????

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值