映射 Map(基本数据类型)(参考张龙老师的)

1.Team.java

package org.yang.hibernate;

import java.util.HashMap;
import java.util.Map;

public class Team
{
    private String id;
    private String teamName;
    private Map students = new HashMap();
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTeamName() {
        return teamName;
    }
    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }
    public Map getStudents() {
        return students;
    }
    public void setStudents(Map students) {
        this.students = students;
    }
    
    
}

2.Team.hbm.xml




    
        
            
        

        
        
            
        

                
        
            
            
            
            
            
        

            
    


3.CreateTable.java

package org.yang.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class CreateTable
{
    public static void main(String[] args)
    {
        SchemaExport export = new SchemaExport(new Configuration().configure());
        export.create(true, true);
    }
}


4. hibernate.cfg.xml




 
        org.postgresql.Driver
        jdbc:postgresql://localhost:5432/myhibernate
        postgres
        yang
        org.hibernate.dialect.PostgreSQLDialect
        thread
        true
        true
        
       
   




5.Test.java

package org.yang.hibernate;

import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test
{
        private static SessionFactory sessionFactory;
        static
        {
            try
            {
                sessionFactory = new Configuration().configure().buildSessionFactory();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        
        public static void main(String[] args)
        {        
            Session session = sessionFactory.openSession();
            Transaction tx = null;
            try
            {
                tx = session.beginTransaction();
                Team team = new Team();
                team.setTeamName("team1");
                
                Map map = team.getStudents();
                map.put("zhanggsan", "helloworld");
                map.put("lisi", "welcome");
                    
                session.save(team);
                tx.commit();
            }
            catch(Exception ex)
            {
                if (null != tx)
                {
                    tx.rollback();
                }
                
                ex.printStackTrace();
            }
            finally
            {
                session.close();
            }

       }

}



你可能感兴趣的:(JavaEE学习,java学习)