hibernate所需要的包
jdbc的驱动
先讲讲两个xml配置文件的dtd约束的位置
config文件用来配置数据库信息以及持久类的映射路径
<?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>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433</property>
<property name="connection.username">数据库的登录名称</property>
<property name="connection.password">密码</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
此处注意需要引入的dtd的xml约束
config对应
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
接下来是持久类的映射信息配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.itcast.entity.user" table="t_user">
<id name="uid" column="uid">
<generator class="native"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
</class>
</hibernate-mapping>
那么它也有对应的dtd约束
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
需要注意的是,两个文件的位置应当在,src/main/resources之下
利用junit进行单元测试
成功连接的话,在console控制台会看到如下信息
此外在连接数据库出现了一个小插曲,在配置信息正确,密码正确的情况下,myeclipse给出了如下报错
Could not obtain connection to query metadata
问题其实出在建立数据库时没有在数据库所有者上勾选你使用的用户名,而是使用了默认