Basic usage example of Hiberate

Source: Internet
Author: User

Basic usage example of Hiberate

The following uses an actual column to demonstrate the basic usage of Hibernate.

Instance:

Package com. ydoing. domain; import java. util. arrayList; import java. util. date; import java. util. hashMap; import java. util. hashSet; import java. util. list; import java. util. map; import java. util. set; import javax. persistence. basic; import javax. persistence. collectionTable; import javax. persistence. column; import javax. persistence. elementCollection; import javax. persistence. entity; import javax. persistence. fetchType; import javax. persistence. generatedValue; import javax. persistence. generationType; import javax. persistence. id; import javax. persistence. joinColumn; import javax. persistence. lob; import javax. persistence. mapKeyClass; import javax. persistence. mapKeyColumn; import javax. persistence. orderColumn; import javax. persistence. table; import javax. persistence. temporal; import javax. persistence. temporalType; import javax. persistence. transient; import org. hibernate. annotations. formula; @ Entity @ Table (name = person) public class Person {// The primary key is ID. It is best to set it to the packaging type Integer @ Id @ Column (name = person_id) @ GeneratedValue (strategy = GenerationType. AUTO) private Integer id; // specify the character length @ Column (name = name, length = 50, nullable = false) private String name; @ Column (name = age) private int age; // you can also choose not to specify the Column name. By default, the attribute name @ Column private String sex of the class is used. // @ Transient indicates that the @ Transient private String alias is not persistent; // @ Lob indicates the big data type, FetchType. LAZY indicates delayed loading to reduce performance overhead @ Lob @ Basic (fetch = FetchType. LAZY) private byte [] image; // specifies the date type @ Temporal (TemporalType. DATE) private Date birthdate; // attribute dynamically generated @ Formula (select concat (p. name, p. age, p. sex) from person p where p. person_id = person_id) private String profile; // List set type // The type of the initialization set needs to be displayed @ ElementCollection (targetClass = String. class) @ CollectionTable (name = pet_inf, // specify the table name // map the foreign key joinColumns = @ JoinColumn (name = person_id, nullable = false )) @ Column (name = pet_name) @ OrderColumn (name = list_order) private List
  
   
Pets = new ArrayList <> (); // array attribute @ ElementCollection (targetClass = String. class) @ CollectionTable (name = school_inf, joinColumns = @ JoinColumn (name = person_id, nullable = false) @ Column (name = school_name) @ OrderColumn (name = array_order) private String [] schools; // Set attributes. The Set attributes are unordered and cannot be repeated, therefore, you do not need to use the @ OrderColumn annotation to map the index column @ ElementCollection (targetClass = String. class) @ CollectionTable (name = car_inf, joinColumns = @ JoinColumn (name = person_id, nullable = false) @ Column (name = car_name) private Set
   
    
Cars = new HashSet <> (); // you must specify the interface implementation class // Map set attribute @ ElementCollection (targetClass = Float. class) @ CollectionTable (name = salary_inf, joinColumns = @ JoinColumn (name = person_id, nullable = false) // specify the key type @ MapKeyColumn (name = salary_type) @ MapKeyClass (String. class) // Map the Map value @ Column (name = money) private Map
    
     
Payroll = new HashMap <> (); // you must specify the interface implementation class // map component attributes. The so-called component means that it is not a basic data type, but a custom composite type, private Address address Address; public address getAddress () {return Address;} public void setAddress (address Address address) {this. address = address;} public Map
     
      
GetPayroll () {return payroll;} public void setPayroll (Map
      
        Payroll) {this. payroll = payroll;} public String [] getSchools () {return schools;} public void setSchools (String [] schools) {this. schools = schools;} public String getSex () {return sex;} public Set
       
         GetCars () {return cars;} public void setCars (Set
        
          Cars) {this. cars = cars;} public void setSex (String sex) {this. sex = sex;} public String getProfile () {return profile;} public void setProfile (String profile) {this. profile = profile;} public Person () {} public int getId () {return id;} public void setId (int 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 String getAlias () {return alias;} public void setAlias (String alias) {this. alias = alias;} public byte [] getImage () {return image;} public void setImage (byte [] image) {this. image = image;} public Date getBirthdate () {return birthdate;} public void setBirthdate (Date birthdate) {this. birthdate = birthdate;} public List
         
           GetPets () {return pets;} public void setPets (List
          
            Pets) {this. pets = pets;} public void setId (Integer id) {this. id = id ;}}
          
         
        
       
      
     
    
   
  

Component class

Package com. ydoing. domain; import javax. persistence. column; import javax. persistence. embeddable; import org. hibernate. annotations. parent; @ Embeddablepublic class Address {@ Column (name = person_province) private String province; @ Column (name = person_city) private String city; public Address () {}// the object component @ Parent private Person person; public Person getPerson () {return person;} public void setPerson (Person person Person) {this. person = person;} public Address (String province, String city) {super (); this. province = province; this. city = city;} public String getProvince () {return province;} public void setProvince (String province) {this. province = province;} public String getCity () {return city;} public void setCity (String city) {this. city = city ;}}

Test:

Package com. ydoing. test; import java. util. arrays; import java. util. list; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. boot. registry. standardServiceRegistryBuilder; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; import com. ydoing. domain. address; import com. ydoing. domain. person; public class Main {public static void main (String [] args) {Configuration conf = new Configuration (); conf. configure (); // ServiceRegistry serviceRegistry = new // ServiceRegistryBuilder (). applySettings (conf. getProperties ())//. buildServiceRegistry (); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder (). applySettings (conf. getProperties ()). build (); SessionFactory factory = conf. buildSessionFactory (serviceRegistry); Session session = factory. openSession (); Person person = new Person (); person. setName (Jack); person. setAge (22); person. setSex (male); // The person is not persistent. setAlias (Arron); // List attribute String [] array = {cat, dog, snake}; List
  
   
Pets = Arrays. asList (array); person. setPets (pets); // array attribute String [] schools = {Tsinghua, Peking University}; person. setSchools (schools); // Set property person. getCars (). add (Audi); person. getCars (). add (public); // Map attribute person. getPayroll (). put (basic salary, (float) 5000); person. getPayroll (). put (performance (float) 3000); person. setAddress (new Address (Zhejiang, Hangzhou); Transaction tx = session. getTransaction (); tx. begin (); session. save (person); Person p = (Person) session. load (Person. class, 12); System. out. println (p. getProfile (); tx. commit (); session. close ();}}
  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.