java+hibernate+mysql

 

实体类News

package org.mythsky.hibernatedemo;

import javax.persistence.*;

@Entity
@Table(name="news_inf")
public class News {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
View Code

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://10.200.151.28/demo</property>
        <property name="connection.username">root</property>
        <property name="connection.password">password</property>

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

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</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="hibernate.format_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <mapping class="org.mythsky.hibernatedemo.News"></mapping>
        <!--<mapping resource="News.hbm.xml"/>-->

    </session-factory>

</hibernate-configuration>
View Code

注意这里IDE会提示

但如果不用这个的话在创建表的时候会报错

测试类NewsManager

package org.mythsky.hibernatedemo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.MetadataSource;
import org.hibernate.service.ServiceRegistry;

public class NewsManager {
    public static void main(String[] args){
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().configure().build();
        SessionFactory sessionFactory=new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction tx=session.beginTransaction();
        News news=new News();
        news.setTitle("my world");
        news.setContent("hello world");
        session.save(news);
        tx.commit();
        session.close();
        sessionFactory.close();
    }
}
View Code

运行可以看到sql

 属性映射

@Formula

@Formula("(select concat(title,content) from news_inf where id=id)")
    private String fullContent;

fullContent字段不会保存在表中,测试

News n=(News)session.get(News.class,1);
        System.out.println(n.getFullContent());

输出

@Transient

使用此注解的字段不会保存在表中

@Enumerated

枚举

public enum Season {
    spring,summer,autumn,winter
}

修改News

@Enumerated(EnumType.ORDINAL)
    private Season season;

EnumType.ORDINAL保存的是枚举的值,例如1,EnumType.STRING保存的是名称,例如spring

@Lob @Basic

@Lob用来保存大数据类型

byte[],Byte[]或java.io.Serializable保存为Blob

char[],Character[]或java.lang.String保存为Clob

@Lob
    @Basic(fetch = FetchType.LAZY)
    private byte[] pic;

@Basic(fetch = FetchType.LAZY)表示延迟加载,@Basic(fetch = FetchType.EAGER,optional = false),optional表示是否允许null

@Temporal

@Temporal(TemporalType.DATE)
    private Date birth;

TemporalType.DATE,TemporalType.TIME,TemporalType.TIMESTAMP分别对应数据库的类型

映射集合属性

List集合

Person.java

package org.mythsky.hibernatedemo;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "person_inf")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private int age;
    @ElementCollection(targetClass = String.class)
    @CollectionTable(name = "school_inf",joinColumns = @JoinColumn(name = "person_id",nullable = false))
    @Column(name = "school_name")
    @OrderColumn(name = "list_order")
    private List<String> schools=new ArrayList<>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<String> getSchools() {
        return schools;
    }

    public void setSchools(List<String> schools) {
        this.schools = schools;
    }

}
View Code

测试PersonManager.java

package org.mythsky.hibernatedemo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class PersonManager {
    public static void main(String[] args){
        SessionFactory sessionFactory;
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            Person person=new Person();
            person.setAge(20);
            person.setName("Tom");
            person.getSchools().add("小学");
            person.getSchools().add("中学");
            session.save(person);
            session.getTransaction().commit();
            session.close();
        }
        catch (Exception e) {
            StandardServiceRegistryBuilder.destroy( registry );
        }
    }
}
View Code

注意在hibernate.cfg.xml中配置

<mapping class="org.mythsky.hibernatedemo.Person"></mapping>

运行后添加了两张表

 map集合

@ElementCollection(targetClass = Float.class)
    @CollectionTable(name = "score_inf",joinColumns = @JoinColumn(name = "person_id",nullable = false))
    @MapKeyColumn(name = "subject_name")
    @MapKeyClass(String.class)
    @Column(name = "mark")
    private Map<String,Float> scores=new HashMap<>();
View Code

修改测试代码

Person person=new Person();
            person.setAge(18);
            person.setName("Jerry");
            person.getSchools().add("小学");
            person.getSchools().add("中学");
            person.getScores().put("语文",90f);
            person.getScores().put("数学",100f);
            session.save(person);
View Code

可以看到新增的表

 联合主键

Person2.java

package org.mythsky.hibernatedemo;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "person_inf2")
public class Person2 implements Serializable {
    @Id
    private String first;
    @Id
    private String last;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person2 person2 = (Person2) o;

        return getFirst().equals(person2.getFirst())&&getLast().equals(person2.getLast());
    }

    @Override
    public int hashCode() {
        int result = getFirst() != null ? getFirst().hashCode() : 0;
        result = 31 * result + (getLast() != null ? getLast().hashCode() : 0);
        return result;
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
View Code

这里采用first和last作为联合主键,需要注意重写equals和hashCode方法。

映射组件属性

Name.java

package org.mythsky.hibernatedemo;

import org.hibernate.annotations.Parent;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Name {
    @Column(name = "fitstname")
    private String first;
    @Column(name = "lastname")
    private String last;
    @Parent
    private Person owner;

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

    public Person getOwner() {
        return owner;
    }

    public void setOwner(Person owner) {
        this.owner = owner;
    }

    public Name(String first, String last) {

        this.first = first;
        this.last = last;
    }

    public Name() {

    }
}
View Code

注意Name需要实现Serializable接口,Person中将原来的String name去掉,换乘Name name;

private Name name;

修改测试代码

Person person=new Person();
            person.setAge(18);
//            person.setName("Jerry");
            Name name=new Name();
            name.setFirst("myth");
            name.setLast("sky");
            person.setName(name);
View Code

运行可以看到如下结果

 

posted @ 2017-11-15 17:48  uptothesky  阅读(606)  评论(0编辑  收藏  举报