最近在学习SSH,现在看到Hibernate这块,动手实现了一个简单的Demo,对Hibernate的功能、使用有了初步了解。 1、首先将Hibernate的jar包复制到Web项目的lib目录下。有些依赖jar包,要额外导入;比如cglib-nodep.jar,不然会报错。 2、配置实体类。这里我用的
最近在学习SSH,现在看到Hibernate这块,动手实现了一个简单的Demo,对Hibernate的功能、使用有了初步了解。
1、首先将Hibernate的jar包复制到Web项目的lib目录下。有些依赖jar包,要额外导入;比如cglib-nodep.jar,不然会报错。
2、配置实体类。这里我用的是一个简单Account类,要注意使用的是javax.persistense.*下面的注解,不是org.hibernate.*下的。
package com.jobhelp.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity //@Entity表示该类能被hibernate持久化 @Table(name="user") //指定Entity对应的数据表名 public class Account { @Id //指定该列为主键 @GeneratedValue(strategy=GenerationType.AUTO) //auto为自增长 private Integer id; @Column(name="name") private String username; @Column(name="password") private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3、在src目录下新建Hibernate的配置文件hibernate.cfg.xml。(MyEclipse向导会自动生成,我用的是Eclipse,就得自己创建了。)
hibernate.cfg.xml的内容如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!--表明以下的配置是针对session-factory配置的,SessionFactory是Hibernate中的一个类,这个类主要负责保存HIbernate的配置信息,以及对Session的操作 --> <session-factory> <!--配置数据库的驱动程序,Hibernate在连接数据库时,需要用到数据库的驱动程序 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property> <!--设置数据库的连接url:jdbc:mysql://localhost/hibernate,其中localhost表示mysql服务器名称,此处为本机, hibernate是数据库名 --> <property name="hibernate.connection.url"> jdbc:mysql://localhost/User </property> <!--连接数据库是用户名 --> <property name="hibernate.connection.username">root </property> <!--连接数据库是密码 --> <property name="hibernate.connection.password">123456 </property> <!--数据库连接池的大小 --> <property name="hibernate.connection.pool.size">20 </property> <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率 --> <property name="hibernate.show_sql">true </property> <!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢 --> <property name="jdbc.fetch_size">50 </property> <!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大 --> <property name="jdbc.batch_size">23 </property> <!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。对分页的结果集。对分页时的设置非常有帮助 --> <property name="jdbc.use_scrollable_resultset">false </property> <!--connection.useUnicode连接数据库时是否使用Unicode编码 --> <property name="Connection.useUnicode">true </property> <!--connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为gbk,用gb2312有的字符不全 --> <!-- <property name="connection.characterEncoding">gbk </property>--> <!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器。 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect </property> <!--指定映射文件为“hibernate/ch1/UserInfo.hbm.xml” --> <!-- <mapping resource="org/mxg/UserInfo.hbm.xml"> --> <mapping class="com.jobhelp.domain.Account"></mapping> </session-factory> </hibernate-configuration>
4、新建Hibernate工具类,用于获取session。Hibernate中每一个session代表一次完整的数据库操作。
Hibernate官方提供的HibernateUtil.java
package com.jobhelp.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory;//单例模式的SessionFactory //static代码块,类加载时初始化hibernate,单例只初始化一次 static{ try{ //从hibernate.cfg.xml中加载配置 //加载@注解配置的实体类用AnnotationConfiguration() //加载xml配置的实体类使用Configuration() sessionFactory = new AnnotationConfiguration() .configure("hibernate.cfg.xml").buildSessionFactory(); } catch (Throwable ex){ System.err.println("Initial SessionFactory Error"); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } }
5、初始化MySql数据库,建一个简单的User表即可,我用的表数据如下。
mysql> select * from user; +----+-------+----------+ | id | name | password | +----+-------+----------+ | 1 | admin | 123456 | | 2 | bowen | 123456 | | 3 | tom | 123456 | | 4 | jack | 123456 | +----+-------+----------+
6、执行hibernate程序。Hibernate是ORM框架,与数据库打交道。
Hibernate中session会话与JDBC操作数据库流程差不多。
相对Spring中jdbcTemplate的使用,hibernate不用写sql语句,不用封装结果;逻辑清晰,代码简洁很多,显然有利于提高开发效率。
下面是在一个Test类中,执行了Hibernate程序的代码。
package com.jobhelp.util; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import com.jobhelp.domain.Account; public class Test { public static void main(String[] agrs){ /*Account account =new Account(); account.setUsername("jack"); account.setPassword("123456");*/ //start a hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); //start a transaction Transaction transaction = session.beginTransaction(); //insert into database //session.persist(account); @SuppressWarnings("all") //hql query List<Account> list =session.createQuery("from Account").list(); //print query result for(Account account2: list){ System.out.println(account2.getId()+" : "+account2.getUsername()); } transaction.commit(); session.close(); } }执行结果:
[2014-11-24 21:26:19,083][DEBUG][org.hibernate.jdbc.AbstractBatcher:366] - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) [2014-11-24 21:26:19,083][DEBUG][org.hibernate.SQL:401] - select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_ Hibernate: select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_ ...... [2014-11-24 21:26:19,108][DEBUG][org.hibernate.engine.StatefulPersistenceContext:787] - initializing non-lazy collections 1 : admin 2 : bowen 3 : tom 4 : jack [2014-11-24 21:26:19,109][DEBUG][org.hibernate.transaction.JDBCTransaction:103] - commit ......
注意:Hibernate只会生成表结构,但不会创建数据库。如果指定数据库不存在,hibernate会抛出异常。

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools
