美文网首页
Hibernate实现简单的用户和角色的增、删、改、查

Hibernate实现简单的用户和角色的增、删、改、查

作者: 爱颠勺的王木木 | 来源:发表于2017-03-10 11:39 被阅读2159次

    最近在学习hibernate,尝试实现简单的增删改查,映射配置。

    现在有两个表,一个user表,一个role表。

    现在要用hibernate进行增删改查功能,首先创建项目,导入需要的包,建好大致的结构。

    现在分别看代码:

    1、hibernate.cfg.xml

    新建xml文件,配置好数据库信息


    <!DOCTYPE hibernate-configuration PUBLIC

     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

     <hibernate-configuration>

     <!-- 配置会话工厂 hibernate 核心 管理数据库连接池 -->

     <session-factory>

      <!-- 1.配置数据库连接参数 -->

      <!-- 1.1配置jdbc四个基本连接参数 -->

      <property name="hibernate.connection.username">root</property>

      <property name="hibernate.connection.password">admin</property>

      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/interview</property>

      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

      <!-- 1.2配置 hibernate使用的方言 -->

      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

      <!-- 2.配置其他相关属性 -->

      <!-- 2.1自动建表 -->

      <property name="hibernate.hbm2ddl.auto">update</property>

      <!-- 2.2在日志中输出sql -->

      <property name="hibernate.show_sql">true</property> 

      <!-- 2.3格式化sql -->

      <property name="hibernate.format_sql">true</property> 

      <!-- 开启事务 -->

      <property name="hibernate.connection.autocommit">true</property>

      <!-- 配置c3p0数据库连接池 -->

      <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

      <property name="hibernate.c3p0.min_size">5</property>

      <property name="hibernate.c3p0.max_size">50</property>

      <property name="hibernate.c3p0.timeout">120</property>

      <property name="hibernate.c3p0.idle_test_period">3000</property>  

      <!-- 3.加载映射文件 -->

      <mapping resource="com/mytest/model/User.hbm.xml"/> 

      <mapping resource="com/mytest/model/Role.hbm.xml"/> 

     </session-factory> 

     </hibernate-configuration>


    2、HibernateUtils.java

    创建HibernateUtils类,创建sessionFactory,读取hibernate.cfg.xml文件,代码中的方法是hibernate4.x的写法,每个版本有所不同,请自行百度搜索。


    packagecom.mytest.util;

    importorg.hibernate.Session;

    importorg.hibernate.SessionFactory;

    importorg.hibernate.boot.registry.StandardServiceRegistryBuilder;

    importorg.hibernate.cfg.Configuration;

    importorg.hibernate.service.ServiceRegistry;

    publicclassHibernateUtils{

    /*

    *读取Hibernate.cfg.xml文件

    */

    privatestaticfinalSessionFactorysessionFactory=buildSessionFactory();

    privatestaticSessionFactorybuildSessionFactory(){

    Configurationcfg=newConfiguration().configure("com/mytest/action/hibernate.cfg.xml");

    ServiceRegistryserviceRegistry=newStandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();

    returncfg.buildSessionFactory(serviceRegistry);

    }

    publicstaticSessionFactorygetSessionFactory(){

    returnsessionFactory;

    }

    }


    3、User.java、Role.java

    新建user bean类,不多解释


    packagecom.mytest.util;

    importjava.util.Date;

    importjava.util.HashSet;

    importjava.util.Set;

    publicclassUser{

    privateIntegeruserId;

    privateStringuserName;

    privateStringemailAddress;

    privateStringpassword;

    privateDatecreateDate;

    privateDatelastUpdateDate;

    privateSetroles=newHashSet();

    publicUser(){

    super();

    }

    publicIntegergetUserId(){

    returnuserId;

    }

    publicvoidsetUserId(IntegeruserId){

    this.userId=userId;

    }

    publicStringgetUserName(){

    returnuserName;

    }

    publicvoidsetUserName(StringuserName){

    this.userName=userName;

    }

    publicStringgetEmailAddress(){

    returnemailAddress;

    }

    publicvoidsetEmailAddress(StringemailAddress){

    this.emailAddress=emailAddress;

    }

    publicStringgetPassword(){

    returnpassword;

    }

    publicvoidsetPassword(Stringpassword){

    this.password=password;

    }

    publicDategetCreateDate(){

    returncreateDate;

    }

    publicvoidsetCreateDate(DatecreateDate){

    this.createDate=createDate;

    }

    publicDategetLastUpdateDate(){

    returnlastUpdateDate;

    }

    publicvoidsetLastUpdateDate(DatelastUpdateDate){

    this.lastUpdateDate=lastUpdateDate;

    }

    publicSetgetRoles(){

    returnroles;

    }

    publicvoidsetRoles(Setroles){

    this.roles=roles;

    }

    }


    packagecom.mytest.util;

    importjava.util.HashSet;

    importjava.util.Set;

    importjavax.persistence.GeneratedValue;

    importjavax.persistence.Id;

    importjavax.persistence.ManyToMany;

    publicclassRole{

    privateIntegerroleId;

    privateStringroleName;

    privateStringdescription;

    privateSetusers=newHashSet();

    publicRole(){

    super();

    }

    publicIntegergetRoleId(){

    returnroleId;

    }

    publicvoidsetRoleId(IntegerroleId){

    this.roleId=roleId;

    }

    publicStringgetRoleName(){

    returnroleName;

    }

    publicvoidsetRoleName(StringroleName){

    this.roleName=roleName;

    }

    publicStringgetDescription(){

    returndescription;

    }

    publicvoidsetDescription(Stringdescription){

    this.description=description;

    }

    publicSetgetUsers(){

    returnusers;

    }

    publicvoidsetUsers(Setusers){

    this.users=users;

    }

    }


    4、User.hbm.xml、Role.hbm.xml

    重点就是映射文件,新建两个xml文件,配置实体和表的映射,这里我用的是many-to-many。

    想法是一个用户可以有多个角色,一个角色也可以对应多个用户。详细看注解。


    <?xml version="1.0"?>

    <!DOCTYPE hibernate-mapping PUBLIC

            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    <hibernate-mapping package="com.mytest.model">

            <class name="com.mytest.util.User" table="user">

             <id name="userId" column="userId" type="integer">

                 <generator class="increment"></generator>

             </id>

             <property name="userName"  type="string">

                 <column name="userName"></column>

             </property>

             <property name="emailAddress"  type="string">

                 <column name="emailAddress"></column>

             </property>

             <property name="password"  type="string">

                 <column name="password"></column>

             </property>

             <property name="createDate"  type="date">

                 <column name="createDate"></column>

             </property>

             <property name="lastUpdateDate"  type="date">

                 <column name="lastUpdateDate"></column>

             </property>

    <!--类User中的集合名为roles。关联表名为:user_role-->

             <set name="roles"  table="user_role">  

    <!--将字段user_id加入user_role表中,作为外键,并指向User对应的表中字段-->

                <key column="user_id"/>

    <!--集合roles成员的类型为Role;将字段role_id加入user_role表中-->

                <many-to-many class="com.mytest.util.Role" column="role_id" />

            </set>

         </class>

    </hibernate-mapping>


    <?xml version="1.0"?>

    <!DOCTYPE hibernate-mapping PUBLIC

            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    <hibernate-mapping package="com.mytest.model">

            <class name="com.mytest.util.Role" table="role">

             <id name="roleId" column="roleId" type="integer">

                 <generator class="increment"></generator>

             </id>

             <property name="roleName"  type="string">

                 <column name="roleName"></column>

             </property>

             <property name="description"  type="string">

                 <column name="description"></column>

             </property>

          <!--类Role中的集合名为users。关联表名为:user_role-->

              <set name="users" table="user_role" >  

          <!--将字段role_id加入user_role表中,作为外键,并指向Role对应的表中字段-->

                <key column="role_id" not-null="true"/>  

         <!--集合users成员的类型为User;将字段user_id加入user_role表中-->

                <many-to-many column="user_id" class="com.mytest.util.User" />

              </set> 

         </class>

    </hibernate-mapping>


    5、Test.java

    最后建一个测试类,写好增删改查的方法


    packagecom.mytest.action;

    importjava.util.Date;

    importjava.util.HashSet;

    importjava.util.Iterator;

    importjava.util.List;

    importjava.util.Set;

    importorg.hibernate.Query;

    importorg.hibernate.Session;

    importorg.hibernate.SessionFactory;

    importcom.mytest.util.HibernateUtils;

    importcom.mytest.util.Role;

    importcom.mytest.util.User;

    publicclassTest{

    privateSessionFactorysessionFactory=HibernateUtils.getSessionFactory();

    /**

    * 1、增加User张三

    */

    publicvoidaddUser(){

    Sessionsession=sessionFactory.openSession();

    session.beginTransaction();

    Useruser=newUser();

    user.setUserId(1);

    user.setUserName("张三");

    user.setEmailAddress("zhang3@sina.com");

    user.setPassword("123456");

    user.setCreateDate(newDate());

    user.setLastUpdateDate(newDate());

    session.save(user);

    session.getTransaction().commit();

    session.close();

    }

    /**

    * 2、增加Role

    */

    publicvoidaddRole(){

    Sessionsession=sessionFactory.openSession();

    session.beginTransaction();

    Rolerole=newRole();

    role.setRoleId(1);

    role.setRoleName("Admin");

    role.setDescription("拥有最高权限");

    session.save(role);

    Rolerole2=newRole();

    role2.setRoleId(2);

    role2.setRoleName("Editor");

    role2.setDescription("拥有编辑者权限");

    session.save(role2);

    Rolerole3=newRole();

    role3.setRoleId(3);

    role3.setRoleName("Reader");

    role3.setDescription("拥有只读权限");

    session.save(role3);

    session.getTransaction().commit();

    session.close();

    }

    /**

    * 3、查询用户张三的信息

    */

    publicvoidselectUser(){

    Sessionsession=sessionFactory.openSession();

    session.beginTransaction();

    Queryquery=session.createQuery("from User where userId= '1'");

    Listlist=query.list();

    for(Useruser:list){

    System.out.println("用户ID:"+user.getUserId());

    System.out.println("用户姓名:"+user.getUserName());

    System.out.println("邮箱:"+user.getEmailAddress());

    System.out.println("密码:"+user.getPassword());

    System.out.println("创建日期:"+user.getCreateDate());

    System.out.println("最后更新日:"+user.getLastUpdateDate());

    }

    session.getTransaction().commit();

    session.close();

    }

    /**

    * 4、更新用户张三的名字和密码

    */

    publicvoidupdateUser(){

    Sessionsession=sessionFactory.openSession();

    session.beginTransaction();

    Useruser=(User)session.get(User.class,1);

    user.setPassword("abcdefg");

    session.update(user);

    session.getTransaction().commit();

    System.out.println("成功更新"+"【"+user.getUserName()+"】"+"的信息!");

    System.out.println("用户ID:"+user.getUserId());

    System.out.println("用户姓名:"+user.getUserName());

    System.out.println("邮箱:"+user.getEmailAddress());

    System.out.println("密码:"+user.getPassword());

    System.out.println("创建日期:"+user.getCreateDate());

    System.out.println("最后更新日:"+user.getLastUpdateDate());

    session.close();

    }

    /**

    * 5、删除张三信息

    */

    publicvoiddeleteUser(){

    Sessionsession=sessionFactory.openSession();

    session.beginTransaction();

    Useruser=(User)session.get(User.class,"1");

    session.delete(user);

    session.getTransaction().commit();

    System.out.println("成功删除"+"【"+user.getUserName()+"】"+"的信息!");

    session.close();

    }

    /**

    * 6、新建李四、王五并赋予角色为Admin

    */

    public void addUserAndRole() {  

    Session session = sessionFactory.openSession();  

        session.beginTransaction();  

            User user2 = new User(); 

            user2.setUserName("李四");  

            user2.setEmailAddress("li4@sina.com");

            user2.setPassword("123456");

            user2.setCreateDate(new Date());  

            user2.setLastUpdateDate(new Date()); 

            User user3 = new User();   

            user3.setUserName("王五");  

            user3.setEmailAddress("wang5@sina.com");

            user3.setPassword("123456");

            user3.setCreateDate(new Date());  

            user3.setLastUpdateDate(new Date()); 

            Role role = new Role(); 

            role.setRoleName("Admin");  

            role.setDescription("拥有最高权限");     

            session.save(role);         

            Role role2 = new Role(); 

            role2.setRoleName("Editor");  

            role2.setDescription("拥有编辑者权限");

            session.save(role2); 

            Role role3 = new Role(); 

            role3.setRoleName("Reader");  

            role3.setDescription("拥有只读权限");

            session.save(role3);       

            Set<Role> u2Roles  = new HashSet<Role>();   

           u2Roles.add(role);

            user2.setRoles(u2Roles);

            session.save(user2);

            Set<Role> u3Roles  = new HashSet<Role>();

            u3Roles.add(role);

            user3.setRoles(u3Roles);

            session.save(user3);

            session.getTransaction().commit();  

            session.close();

            System.out.println("成功分配给"+ user2.getUserName()+"【"+role.getRoleName()+"】"+"权限!");

            System.out.println("成功分配给"+ user3.getUserName()+"【"+role.getRoleName()+"】"+"权限!");

      }

    /**

    * 7、根据角色主键Admin查询该角色下所有的用户信息

    */

    publicvoidselectUserByRole(){

    Sessionsession=sessionFactory.openSession();

    session.beginTransaction();

    Queryquery=session.createQuery("SELECT "

    +"u.userId,"

    +"u.userName,"

    +"u.emailAddress,"

    +"u.password,"

    +"u.createDate,"

    +"u.lastUpdateDate "

    +"FROM User u WHERE u.userId IN (SELECT ur.user_id FROM user_role ur WHERE ur.role_id = '1'");

    Listlist=query.list();

    for(Useruser:list){

    System.out.println("用户ID:"+user.getUserId());

    System.out.println("用户姓名:"+user.getUserName());

    System.out.println("邮箱:"+user.getEmailAddress());

    System.out.println("密码:"+user.getPassword());

    System.out.println("创建日期:"+user.getCreateDate());

    System.out.println("最后更新日:"+user.getLastUpdateDate());

    }

    session.getTransaction().commit();

    session.close();

    /*List list = query.list();

    Iterator it= list.iterator();

    while(it.hasNext()){

    User user=(User)it.next();

    System.out.println("用户ID:"+ user.getUserId());

    System.out.println("用户姓名:"+user.getUserName());

    System.out.println("邮箱:"+user.getEmailAddress());

    System.out.println("密码:"+user.getPassword());

    System.out.println("创建日期:"+ user.getCreateDate());

    System.out.println("最后更新日:"+ user.getLastUpdateDate());

    }*/

    }

    /**

    * 主函数

    */

    publicstaticvoidmain(String[]args){

    newTest().addUser();

    newTest().addRole();

    newTest().selectUser();

    newTest().updateUser();

    newTest().deleteUser();

    newTest().addUserAndRole();

    newTest().selectUserByRole();

    }

    }


    执行结果:

    1、


    2、


    3、


    4、


    5、


    6、这里我把第3个addRole放到一起了,也可以单独取权限Id赋值。

    这里运行完,系统生成了一个关联表,就是我们再xml文件里配置的user_id表。

    相关文章

      网友评论

          本文标题:Hibernate实现简单的用户和角色的增、删、改、查

          本文链接:https://www.haomeiwen.com/subject/gupngttx.html