Hibernate框架认识之建立用户角色权限三者关系

每个项目都有关于用户角色权限三者之间关系,这也是对每一个程序员的基本要求。现在很多程度上都是使用Hibernate框架。那先我们认识一下,什么是Hibernate框架

1、Hibernate的定义:

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。

2、ORM概述:

ObjectRelativeMapping即对象关系映射,ORM是一种思想,关注的是对象与数据库中的列的关系

下面我们举个列子:用户角色权限三者之间怎么用Hibernate建表

首先 配置db.properties文件

#<!-- 数据库连接设置 -->
#<!-- 数据库连接驱动 -->
#SQLSERVER
connection.mysql.driver_class=com.mysql.jdbc.Driver
#<!-- 数据库连接URL -->
connection.url=jdbc\:mysql\://localhost\:3306/MySQL?useUnicode\=true&amp;characterEncoding\=utf-8&autoReconnect=true&failOverReadOnly=false&amp;useSSL=false
#<!-- 用户名 -->
connection.name=XXX
connection.password=XXX

#<!-- SQL dialect -->
hibernate.dialect =org.hibernate.dialect.MySQL5Dialect

# <!-- Enable Hibernate's automatic session context management -->
hibernate.cache.use_query_cache=false
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_structured_entries=false
hibernate.cache.region.factory_class=org.hibernate.cache.EhCacheRegionFactory
#hibernate.net.sf.ehcache.configurationResourceName==

#<!-- Echo all executed SQL to stdout -->
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update

其次,就是配置XML文件。项目中我们一般会使用Spring、SpringMVC、Hibernate或者Spring、SpringMVC、Mybatis框架组合使用,我是在applicationContext.xml文件中配置Hibernate的信息

<!-- 配置工厂类 -->
    <!-- SessionFactory -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.yyf.tax.entity</value>
            </list>
        </property>
    </bean>

    <!-- 事务的配置 -->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
        <property name="globalRollbackOnParticipationFailure" value="false" />
    </bean>

pom.xml引入Hibernate的依赖

<hibernate.core.version>4.3.10.Final</hibernate.core.version>
      <hibernate.validator.version>4.3.1.Final</hibernate.validator.version>



<!-- hibernate-->
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>${hibernate.core.version}</version>
      </dependency>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-entitymanager</artifactId>
          <version>${hibernate.core.version}</version>
      </dependency>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>${hibernate.validator.version}</version>
      </dependency>

最后,万事俱备只欠东风,下面就可以大刀阔斧的建表啦

用户表

@Entity
@Table(name="tax_user")
@Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
public class User extends BaseEntity{

	private static final long serialVersionUID = 1L;

    /** 用户名 **/
    @Column(name = "username",nullable = false,unique = true)
    private String username;

    /** 密码 **/
    @Column(name = "password",nullable = false)
    private String password;

    /** 姓名 */
    @Column(name = "name")
    private String name;

    /** 联系方式 **/
    @Column(name = "mobile")
    private String mobile;

    /** 邮箱 **/
    @Column(name = "email")
    private String email;

    /** 用户类型  **/
    @Enumerated(EnumType.STRING)
    @Column(name = "user_type")
    private UserTypeEnum userType;

    /** 用户状态  **/
    @Enumerated(EnumType.STRING)
    @Column(name = "user_status")
    private UserStatusEnum userStatus;


    /**产品**/
    @ManyToOne(targetEntity = Product.class ,optional = true ,fetch = FetchType.EAGER)
    @JoinColumn(name = "product_id",updatable = true ,insertable = true ,nullable = true)
    private Product product;

    /** 多对多 */
    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @JoinTable(name="eb_user_role",joinColumns={@JoinColumn(name="user_id",updatable=false)
    },inverseJoinColumns={@JoinColumn(name="role_id",updatable=false)}
    )
    private Set<Role> roles = new HashSet<Role>();

实体类:角色

@Entity
@Table(name="tax_role")
@Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
public class Role extends BaseEntity{

    @Column(name = "role_name")
    private String roleName;

    @Column(name = "role_sign")
    private String roleSign;

    @Column(name = "description")
    private String description;

    /** 多对多 */
    @ManyToMany(mappedBy="roles")
    @Fetch(FetchMode.SELECT)
    private Set<User> users = new HashSet<User>();

    /** 多对多 */
    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @JoinTable(name="eb_role_permission",joinColumns={@JoinColumn(name="role_id",updatable=false)
    },inverseJoinColumns={@JoinColumn(name="permission_id",updatable=false)}
    )
    private Set<Permission> permissions = new HashSet<Permission>();


    @Override
    public String toString() {
        return "Role [id=" + getId() + ", roleName=" + roleName + ", roleSign=" + roleSign + ", description=" + description + "]";
    }

实体类:权限

@Entity
@Table(name="tax_permission")
@Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
public class Permission extends BaseEntity{

    @Column(name = "permission_name")
    private String permissionName;

    @Column(name = "permission_sign")
    private String permissionSign;

    @Column(name = "description")
    private String description;


    /** 多对多 */
    @ManyToMany(mappedBy = "permissions")
    @Fetch(FetchMode.SELECT)
    private Set<Role> roles = new HashSet<Role>();


    @Override
    public String toString() {
        return "Permission [id=" + getId() + ", permissionName=" + permissionName + ", permissionSign=" + permissionSign + ", description=" + description + "]";
    }

项目启动的时候就可以在你的数据库中自动创建列,如果在项目中要求字段大小,可以在注解中增加 length = ?属性。

这样,用户角色权限三者之间的关系就可以在数据库中显示出来,这就是ORM一种思想的实现。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值