hibernate中Modle的属性名称和数据字段名称配置的方法

在hibernate中有的时候数据的字段的名称带有下划线或者其他符号,这样你在Modle里定义属性的时候按照数据库字段定义属性总觉的不符合Java的命名规范,如何在Mole里对属性指定数据库的字段的名称呢?今天来看看。

第一步:创建Java工程创建项目包在本例中创建三个包com.ygc.hibernate.main | com.ygc.hibernate.modle | com.ygc.hibernate.utils并且编写modle类,Modle类的类名Product模拟一个产品表。

package com.ygc.hibernate.modle;

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
@Table(name="Product")
public class Product {
	private int id;
	private String productName;
	private int productPrice;
	private String productType;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO) //设置主键自动增长
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	//这里是主要的配置了如果数据库字段和属性名称不一样是在这里指定数据库的字段的名称
	@Column(name="product_name")
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	public int getProductPrice() {
		return productPrice;
	}
	public void setProductPrice(int productPrice) {
		this.productPrice = productPrice;
	}
	public String getProductType() {
		return productType;
	}
	public void setProductType(String productType) {
		this.productType = productType;
	}
}

 

第二步:编写测试类和工具类

package com.ygc.hibernate.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ygc.hibernate.modle.Product;
import com.ygc.hibernate.utils.HibernateUtils;

public class ProductTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Product product = new Product();
		product.setProductName("Iphone4s");
		product.setProductPrice(5000);
		product.setProductType("智能手机");
		
		SessionFactory sFactory = HibernateUtils.getHibernateUtils().getSessionFactory();
		Session session = sFactory.openSession();
		session.beginTransaction();
		session.save(product);
		session.getTransaction().commit();
	}

}

工具类

package com.ygc.hibernate.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
	private static HibernateUtils instance;
	
	public static HibernateUtils getHibernateUtils(){
		if(instance==null){
			instance=new HibernateUtils();
		}
		return instance;
	}
	
	public SessionFactory getSessionFactory(){
		Configuration configuration = new AnnotationConfiguration().configure();
		return configuration.buildSessionFactory();
	}
}

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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!--<property name="connection.pool_size">1</property>-->

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

        <!-- Enable Hibernate's automatic session context management -->
        <!--<property name="current_session_context_class">thread</property>-->

        <!-- Disable the second-level cache  -->
        <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>-->

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!--自动创建表-->
       <property name="hbm2ddl.auto">create</property>

        <!-- Drop and re-create the database schema on startup -->
        <!--<property name="hbm2ddl.auto">update</property>-->

        <!--<mapping resource="com/ygc/hibernate/modle/Students.hbm.xml"/>-->
        <mapping class="com.ygc.hibernate.modle.Music"/>

    </session-factory>

</hibernate-configuration>


log4j配置文件

# Configure logging for testing: optionally with log file
# debug,info,warn,error,fatal
log4j.rootLogger=debug, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=D:/logs/hibernate.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.logger.org.hibernate.tool.hbm2ddl=debug


查看运行结果:

C:\Documents and Settings\Administrator>mysql -uroot -proot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 5.5.15 MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

使用数据库

mysql> use hibernate
Database changed

显示数据库

mysql> show tables;
+---------------------+
| Tables_in_hibernate |
+---------------------+
| music               |
| product             |
| students            |
| teacher             |
| xuxudan             |
+---------------------+
5 rows in set (0.06 sec)

查询数据库

mysql> select * from product
    -> ;
+----+--------------+--------------+-------------+
| id | product_name | productPrice | productType |
+----+--------------+--------------+-------------+
|  1 | Iphone4s     |         5000 | 智能手机    |
+----+--------------+--------------+-------------+
1 row in set (0.02 sec)



Demo下载:下载


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值