温馨提示:您的每一次转载,体现了我写此文的意义!!!烦请您在转载时注明出处http://www.blogjava.net/sxyx2008/谢谢合作!!!

雪山飞鹄

温馨提示:您的每一次转载,体现了我写此文的意义!!!烦请您在转载时注明出处http://www.blogjava.net/sxyx2008/谢谢合作!!!

BlogJava 首页 新随笔 联系 聚合 管理
  215 Posts :: 1 Stories :: 674 Comments :: 0 Trackbacks

#


SQL
create table Roles
(
   id                   
int not null auto_increment,
   name                 
varchar(20),
   
primary key (id)
);

create table Users
(
   id                   
int not null auto_increment,
   name                 
varchar(20),
   
primary key (id)
);

create table user_role
(
   
user_id              int not null,
   role_id              
int not null,
   
primary key (user_id, role_id)
);

alter table user_role add constraint FK_Reference_1 foreign key (user_id)
      
references Users (id) on delete restrict on update restrict;

alter table user_role add constraint FK_Reference_2 foreign key (role_id)
      
references Roles (id) on delete restrict on update restrict;

Role.java
package com.many2many.bean;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name
="roles",catalog="JPA_Many2Many")
public class Role {
    
    
private int id;
    
private String name;
    
private Set<User> users;
    @Id
    @Column(name
="id")
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @ManyToMany(cascade
=CascadeType.PERSIST)
    @JoinTable(
            name
="user_role",
            joinColumns
=@JoinColumn(name="role_id"),
            inverseJoinColumns
=@JoinColumn(name="user_id")
    )
    
public Set<User> getUsers() {
        
return users;
    }
    
public void setUsers(Set<User> users) {
        
this.users = users;
    }
    
}

User.java
package com.many2many.bean;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name
="users",catalog="JPA_Many2Many")
public class User {
    
    
private int id;
    
private String name;
    
private Set<Role> roles;
    @Id
    @Column(name
="id")
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @ManyToMany(mappedBy
="users",cascade=CascadeType.REFRESH)
    
public Set<Role> getRoles() {
        
return roles;
    }
    
public void setRoles(Set<Role> roles) {
        
this.roles = roles;
    }
    
    
}

JPAUtil.java
package com.many2many.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil {
    
    
private static EntityManager entityManager;
    
public static EntityManager getInstance(){
        
if(entityManager!=null){
            
return entityManager;
        }
else{
            
return makeInstance();
        }
    }
    
private static synchronized EntityManager makeInstance() {
        
if(entityManager==null){
            EntityManagerFactory entityManagerFactory
=Persistence.createEntityManagerFactory("JPA_Many2ManyPU");
            
return entityManagerFactory.createEntityManager();
        }
        
return null;
    }
}

测试代码
@Test
    
public void insert(){
        EntityManager entityManager
=JPAUtil.getInstance();
        EntityTransaction entityTransaction
=entityManager.getTransaction();
        
try {
            entityTransaction.begin();
            
            User user
=new User();
            user.setName(
"张三");
            
            Role role
=new Role();
            role.setName(
"管理员");
            
            Set
<User> users=new HashSet<User>();
            users.add(user);
            
            role.setUsers(users);
            
            entityManager.persist(role);
            
            entityTransaction.commit();
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Test
    
public void select(){
        EntityManager entityManager
=JPAUtil.getInstance();
        Role role
=entityManager.find(Role.class1);
        System.out.println(role.getName());
        Set
<User> set=role.getUsers();
        
for (Iterator<User> iterator = set.iterator(); iterator.hasNext();) {
            User user 
= (User) iterator.next();
            System.out.println(user.getName());
        }
    }
posted @ 2010-10-18 20:44 雪山飞鹄 阅读(1971) | 评论 (0)编辑 收藏


Department.java
package com.many2one.bean;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name
="department",catalog="Hibernate_Many2One")
public class Department {
    
    
private int id;
    
private String name;
    
private Set<Employee> sets;
    @Id
    @GeneratedValue(strategy
=GenerationType.AUTO)
    @Column(name
="id")
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @OneToMany(mappedBy
="department")
    
public Set<Employee> getSets() {
        
return sets;
    }
    
public void setSets(Set<Employee> sets) {
        
this.sets = sets;
    }
    
}
Employee.java
package com.many2one.bean;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name
="employee",catalog="Hibernate_Many2One")
public class Employee {
    
    
private int id;
    
private String name;
    
private Department department;
    @Id
    @Column(name
="id")
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @ManyToOne(cascade
=CascadeType.ALL)
    @JoinColumn(name
="deptid")
    
public Department getDepartment() {
        
return department;
    }
    
public void setDepartment(Department department) {
        
this.department = department;
    }
    
    
}
导出的sql
create table Hibernate_Many2One.department (
        id 
integer not null auto_increment,
        name 
varchar(255),
        
primary key (id)
    )

    
create table Hibernate_Many2One.employee (
        id 
integer not null auto_increment,
        name 
varchar(255),
        deptid 
integer,
        
primary key (id)
    )

    
alter table Hibernate_Many2One.employee 
        
add index FK4722E6AE3829E242 (deptid), 
        
add constraint FK4722E6AE3829E242 
        
foreign key (deptid) 
        
references Hibernate_Many2One.department (id)

测试代码
@Test
    
public void insert(){
        Session session
=HibernateSessionFactory.getSession();
        Transaction transaction
=session.beginTransaction();
        
try {
            transaction.begin();
            Department department
=new Department();
            department.setName(
"软件测试部");
            Employee employee
=new Employee();
            employee.setName(
"张三");
            employee.setDepartment(department);
            session.save(employee);
            transaction.commit();
        } 
catch (HibernateException e) {
            e.printStackTrace();
        }
    }
    
    
    @Test
    
public void select(){
        Session session
=HibernateSessionFactory.getSession();
        
try {
            Employee employee
=(Employee) session.get(Employee.class1);
            System.out.println(employee.getName());
            System.out.println(employee.getDepartment().getName());
        } 
catch (HibernateException e) {
            e.printStackTrace();
        }
    }
posted @ 2010-10-18 15:46 雪山飞鹄 阅读(1470) | 评论 (1)编辑 收藏


Department.java
package com.many2one.bean;

import java.util.Set;

public class Department {
    
    
private int id;
    
private String name;
    
private Set<Employee> sets;
    
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 Set<Employee> getSets() {
        
return sets;
    }
    
public void setSets(Set<Employee> sets) {
        
this.sets = sets;
    }
    
}
Employee.java
package com.many2one.bean;


public class Employee {
    
    
private int id;
    
private String name;
    
private Department department;
    
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 Department getDepartment() {
        
return department;
    }
    
public void setDepartment(Department department) {
        
this.department = department;
    }
    
    
}
映射文件
Department.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
    
<hibernate-mapping package="com.many2one.bean">
        
<class name="Department" table="department" catalog="Hibernate_Many2One">
            
<id name="id" column="id">
                
<generator class="native"/>
            
</id>
            
<property name="name" column="name"/>
            
        
</class>
    
</hibernate-mapping>
Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
    
<hibernate-mapping package="com.many2one.bean">
        
<class name="Employee" table="employee" catalog="Hibernate_Many2One">
            
<id name="id" column="id">
                
<generator class="native"/>
            
</id>
            
<property name="name" column="name"/>
            
<many-to-one name="department" column="deptid" cascade="all" />
        
</class>
    
</hibernate-mapping>
导出的sql
create table Hibernate_Many2One.department (
        id 
integer not null auto_increment,
        name 
varchar(255),
        
primary key (id)
    )

    
create table Hibernate_Many2One.employee (
        id 
integer not null auto_increment,
        name 
varchar(255),
        deptid 
integer,
        
primary key (id)
    )

    
alter table Hibernate_Many2One.employee 
        
add index FK4722E6AE3829E242 (deptid), 
        
add constraint FK4722E6AE3829E242 
        
foreign key (deptid) 
        
references Hibernate_Many2One.department (id)

测试代码
@Test
    
public void insert(){
        Session session
=HibernateSessionFactory.getSession();
        Transaction transaction
=session.beginTransaction();
        
try {
            transaction.begin();
            Department department
=new Department();
            department.setName(
"软件测试部");
            Employee employee
=new Employee();
            employee.setName(
"张三");
            employee.setDepartment(department);
            session.save(employee);
            transaction.commit();
        } 
catch (HibernateException e) {
            e.printStackTrace();
        }
    }
    
    
    @Test
    
public void select(){
        Session session
=HibernateSessionFactory.getSession();
        
try {
            Employee employee
=(Employee) session.get(Employee.class1);
            System.out.println(employee.getName());
            System.out.println(employee.getDepartment().getName());
        } 
catch (HibernateException e) {
            e.printStackTrace();
        }
    }
posted @ 2010-10-18 15:40 雪山飞鹄 阅读(2341) | 评论 (0)编辑 收藏


Husband.java
package com.one2one.bean;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name
="husband",catalog="Hibernate_One2One_fk")
public class Husband {
    
    
private int id;
    
private String name;
    
private Wife wife;
    @Id
    @Column(name
="id")
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @OneToOne(cascade
=CascadeType.ALL,mappedBy="husband")
    
public Wife getWife() {
        
return wife;
    }
    
public void setWife(Wife wife) {
        
this.wife = wife;
    }
    
}
Wife.java
package com.one2one.bean;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name
="wife",catalog="Hibernate_One2One_fk")
public class Wife {
    
    
private int id;
    
private String name;
    
private Husband husband;
    @Id
    @Column(name
="id")
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @OneToOne(cascade
=CascadeType.ALL)
    @JoinColumn(name
="husband_id")
    
public Husband getHusband() {
        
return husband;
    }
    
public void setHusband(Husband husband) {
        
this.husband = husband;
    }
    
}

导出的sql
create table Hibernate_One2One_fk.husband (
        id 
integer not null auto_increment,
        name 
varchar(255),
        
primary key (id)
    )

    
create table Hibernate_One2One_fk.wife (
        id 
integer not null auto_increment,
        name 
varchar(255),
        husband_id 
integer,
        
primary key (id)
    )

    
alter table Hibernate_One2One_fk.wife 
        
add index FK37AF119039AEDD (husband_id), 
        
add constraint FK37AF119039AEDD 
        
foreign key (husband_id) 
        
references Hibernate_One2One_fk.husband (id)

测试代码
@Test
    
public void save(){
        Session session
=HibernateSessionFactory.getSession();
        Transaction transaction
=session.beginTransaction();
        
try {
            transaction.begin();
            Husband husband
=new Husband();
            husband.setName(
"张三");
            session.save(husband);
            Wife wife
=new Wife();
            wife.setName(
"如花");
            wife.setHusband(husband);
            session.save(wife);
            transaction.commit();
        } 
catch (HibernateException e) {
            e.printStackTrace();
        }
    }
    
    @Test
    
public void select(){
        Session session
=HibernateSessionFactory.getSession();
        Husband husband
=(Husband) session.get(Husband.class1);
        System.out.println(husband.getName());
        System.out.println(husband.getWife().getName());
    }
posted @ 2010-10-18 14:29 雪山飞鹄 阅读(1446) | 评论 (0)编辑 收藏


Husband.java
package com.one2one.bean;


public class Husband {
    
    
private int id;
    
private String name;
    
private Wife wife;
    
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 Wife getWife() {
        
return wife;
    }
    
public void setWife(Wife wife) {
        
this.wife = wife;
    }
    
}
Wife.java
package com.one2one.bean;

public class Wife {
    
    
private int id;
    
private String name;
    
private Husband husband;
    
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 Husband getHusband() {
        
return husband;
    }
    
public void setHusband(Husband husband) {
        
this.husband = husband;
    }
    
}
映射文件
Husband.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
    
<hibernate-mapping package="com.one2one.bean">
        
<class name="Husband" table="husband" catalog="Hibernate_One2One_fk">
            
<id name="id" column="id">
                
<generator class="native"/>
            
</id>
            
<property name="name" column="name"/>
            
<one-to-one name="wife" class="Wife" property-ref="husband"/>
        
</class>
    
</hibernate-mapping>
<one-to-one name="wife" class="Wife" property-ref="husband"/> property-ref后的husband为Wife中定义的husband属性
Wife.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
    
<hibernate-mapping package="com.one2one.bean">
        
<class name="Wife" table="wife" catalog="Hibernate_One2One_fk">
            
<id name="id" column="id">
                
<generator class="native"/>
            
</id>
            
<property name="name" column="name"/>
            
<many-to-one name="husband" column="husband_id" unique="true" />
        
</class>
    
</hibernate-mapping>
<many-to-one name="husband" column="husband_id" unique="true" />
many-to-one的作用是在wife表中生成一个外键husband_id,且唯一,并参照husband表中的主键
用hibernate的hbm2ddl导出的sql
create table Hibernate_One2One_fk.husband (
        id 
integer not null auto_increment,
        name 
varchar(255),
        
primary key (id)
    )

    
create table Hibernate_One2One_fk.wife (
        id 
integer not null auto_increment,
        name 
varchar(255),
        husband_id 
integer unique,
        
primary key (id)
    )

    
alter table Hibernate_One2One_fk.wife 
        
add index FK37AF119039AEDD (husband_id), 
        
add constraint FK37AF119039AEDD 
        
foreign key (husband_id) 
        
references Hibernate_One2One_fk.husband (id)

测试示例
@Test
    
public void save(){
        Session session
=HibernateSessionFactory.getSession();
        Transaction transaction
=session.beginTransaction();
        
try {
            transaction.begin();
            Husband husband
=new Husband();
            husband.setName(
"张三");
            session.save(husband);
            Wife wife
=new Wife();
            wife.setName(
"如花");
            wife.setHusband(husband);
            session.save(wife);
            transaction.commit();
        } 
catch (HibernateException e) {
            e.printStackTrace();
        }
    }
    
    @Test
    
public void select(){
        Session session
=HibernateSessionFactory.getSession();
        Husband husband
=(Husband) session.get(Husband.class1);
        System.out.println(husband.getName());
        System.out.println(husband.getWife().getName());
    }

posted @ 2010-10-18 14:17 雪山飞鹄 阅读(6111) | 评论 (0)编辑 收藏


SQL
create table Department
(
   id                   
int not null auto_increment,
   name                 
varchar(20),
   
primary key (id)
);

create table Employee
(
   id                   
int not null auto_increment,
   name                 
varchar(20),
   deptid               
int,
   
primary key (id)
);

alter table Employee add constraint FK_Reference_1 foreign key (deptid)
      
references Department (id) on delete restrict on update restrict;
Department.java
package com.many2one.bean;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@SuppressWarnings(
"serial")
@Entity
@Table(name
="department",catalog="jpa_many2one")
public class Department  implements Serializable{
    
    
private int id;
    
private String name;
    
private Set<Employee> sets;
    @Id
    @GeneratedValue(strategy
=GenerationType.AUTO)
    @Column(name
="id")
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @OneToMany(mappedBy
="department")
    
public Set<Employee> getSets() {
        
return sets;
    }
    
public void setSets(Set<Employee> sets) {
        
this.sets = sets;
    }
    
    
}
Employee.java
package com.many2one.bean;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name
="employee",catalog="jpa_many2one")
public class Employee {
    
    
private int id;
    
private String name;
    
private Department department;
    @Id
    @GeneratedValue(strategy
=GenerationType.AUTO)
    @Column(name
="id")
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    @Column(name
="name")
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    @ManyToOne(cascade
=CascadeType.ALL)
    @JoinColumn(name
="deptid")
    
public Department getDepartment() {
        
return department;
    }
    
public void setDepartment(Department department) {
        
this.department = department;
    }
    
    
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version="1.0">
    
    
<persistence-unit name="JPA_Many2OnePU" transaction-type="RESOURCE_LOCAL">
        
<provider>org.hibernate.ejb.HibernatePersistence</provider>
        
<class>com.many2one.bean.Department</class>
        
<class>com.many2one.bean.Employee</class>
          
<properties>
            
<property name = "hibernate.connection.driver_class" value = "com.mysql.jdbc.Driver"/>
            
<property name = "hibernate.connection.url" value = "jdbc:mysql://localhost:3306/jpa_many2one"/>
            
<property name = "hibernate.connection.username" value = "root"/>
            
<property name = "hibernate.connection.password" value = "root"/>
            
<property name = "hibernate.show_sql" value = "true"/>
            
<property name = "hibernate.format_sql" value = "true"/>
          
</properties>
    
</persistence-unit>
  
</persistence>
JPAUtil.java
package com.many2one.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil {
    
    
private static EntityManager entityManager;
    
public static EntityManager getInstance(){
        
if(entityManager!=null){
            
return entityManager;
        }
else{
            
return makeInstance();
        }
    }
    
private static synchronized EntityManager makeInstance() {
        
if(entityManager==null){
            EntityManagerFactory entityManagerFactory
=Persistence.createEntityManagerFactory("JPA_Many2OnePU");
            
return entityManagerFactory.createEntityManager();
        }
        
return null;
    }
}

@Test
    
public void select(){
        EntityManager entityManager
=JPAUtil.getInstance();
        Employee employee
=entityManager.find(Employee.class1);
        System.out.println(
"雇员是:"+employee.getName());
        System.out.println(
"部门是:"+employee.getDepartment().getName());
    }
    
    @Test
    
public void insert(){
        EntityManager entityManager
=JPAUtil.getInstance();
        EntityTransaction entityTransaction
=entityManager.getTransaction();
        
try {
            entityTransaction.begin();
            Department department
=new Department();
            department.setName(
"软件研发部");
            Employee employee
=new Employee();
            employee.setName(
"张三");
            employee.setDepartment(department);
            entityManager.persist(employee);
            entityTransaction.commit();
        } 
catch (Exception e) {
            e.printStackTrace();
            entityTransaction.rollback();
        }
    }
posted @ 2010-10-17 16:36 雪山飞鹄 阅读(2620) | 评论 (0)编辑 收藏

此文转自http://linder.javaeye.com/blog/782071
一、Tomcat 安装后本身提供了一个server,端口配置默认是8080,对应目录为:..\Tomcat 6.0\webapps
二、Tomcat 6.0 配置多个端口,其实也就是给Tomcat增加几个server,并设置对应目录。下面以增加两个端口号为例
第一步、修改server.xml[..\Tomcat 6.0\conf]
(1)Tomcat提供的如下:
<Service name="Catalina">
   
    
<Connector port="8090" maxHttpHeaderSize="8192"
               maxThreads
="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups
="false" redirectPort="8443" acceptCount="100"
               connectionTimeout
="20000" disableUploadTimeout="true" />
    
    
<Connector port="8009" 
               enableLookups
="false" redirectPort="8443" protocol="AJP/1.3" />


    
<Engine name="Catalina" defaultHost="localhost">


      
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName
="UserDatabase"/>
      
      
<Host name="localhost" appBase="webapps"
       unpackWARs
="true" autoDeploy="true"
       xmlValidation
="false" xmlNamespaceAware="false">              
      
</Host>


    
</Engine>


</Service>

(2)比着上面的葫芦画下面的瓢、新增两个端口号,注意Service name、Engine name、appBase,当然了,端口号别忘了修改,以免重复。
<Service name="Catalina1">
   
    
<Connector port="8091" maxHttpHeaderSize="8192"
               maxThreads
="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups
="false" redirectPort="8443" acceptCount="100"
               connectionTimeout
="20000" disableUploadTimeout="true" />
    
    
<Connector port="8009" 
               enableLookups
="false" redirectPort="8443" protocol="AJP/1.3" />


    
<Engine name="Catalina1" defaultHost="localhost">


      
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName
="UserDatabase"/>
      
      
<Host name="localhost" appBase="webapps1"
       unpackWARs
="true" autoDeploy="true"
       xmlValidation
="false" xmlNamespaceAware="false">              
      
</Host>


    
</Engine>


</Service>

<Service name="Catalina2">
   
    
<Connector port="8092" maxHttpHeaderSize="8192"
               maxThreads
="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups
="false" redirectPort="8443" acceptCount="100"
               connectionTimeout
="20000" disableUploadTimeout="true" />
    
    
<Connector port="8009" 
               enableLookups
="false" redirectPort="8443" protocol="AJP/1.3" />


    
<Engine name="Catalina2" defaultHost="localhost">


      
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName
="UserDatabase"/>
      
      
<Host name="localhost" appBase="webapps2"<!-- 这个地方很重要,我今天没修改这个,导致webapps下的几个应用都可以用多个端口访问,结果只好将默认的webapps下的应用拷到其他地方,在${tomcat_home}/conf/下创建Catalina2/localhost/,并创建不同的xml文件将docBase指向应用所在的路径-->
       unpackWARs="true" autoDeploy="true"
       xmlValidation="false" xmlNamespaceAware="false">              
      
</Host>


    
</Engine>


</Service>

第二步、创建相应的部署目录
..\Tomcat 6.0\webapps1
..\Tomcat 6.0\webapps2
同时可以将Tomcat 6.0\webapps下的有用的复制到新建的部署目录

第三步、创建配置文件目录和配置文件
..\Tomcat 6.0\conf\Catalina1\localhost
..\Tomcat 6.0\conf\Catalina2\localhost


host-manager.xml
manager.xml


配置文件的配置可参照..\Tomcat 6.0\conf\Catalina\localhost下的,只需要修改一下对应目录即可


大概的配置步骤就是这些,现在可以把不同的war包放在不同的位置来访问了
以上配置方法同样适合Tomcat 5.5

posted @ 2010-10-16 19:23 雪山飞鹄 阅读(1684) | 评论 (0)编辑 收藏

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist:
此异常多出现在Hibernate、JPA级联映射中,在级联保存时频发
从异常信息不难看出,在进行持久化的时候引用了一个未持久化的对象
或者确定给对象已被持久化了,当再次去引用时,仍包此错误,那么只有一种可能,就是在配置文件里面级联配置的不正确尝试把cascade = CascadeType.ALL 改成 cascade=CascadeType.REFRESH 测一下看看。(适用于Hibernate注解或JPA的级联映射)

posted @ 2010-10-15 13:30 雪山飞鹄 阅读(3961) | 评论 (0)编辑 收藏

java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
环境说明:
该异常出自JPA的事务
产生此异常的原因是因为在项目中将JPA的事务交给spring来管理,即使用了@Transactional注解,而自己手动又在代码中开启了JPA的事务.
解决方案:删除自己手动写的JPA事务代码或去掉@Transactional注解
posted @ 2010-10-15 11:02 雪山飞鹄 阅读(5509) | 评论 (0)编辑 收藏


create table Husband
(
   id                   
int not null auto_increment,
   name                 
varchar(20),
   
primary key (id)
);

create table Wife
(
   id                   
int not null auto_increment,
   name                 
varchar(20),
   husband_id           
int,
   
primary key (id)
);
alter table Wife add constraint FK_Reference_1 foreign key (id)
      
references Husband (id) on delete restrict on update restrict;
Husband
package com.ono2one.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@SuppressWarnings(
"serial")
@Entity
@Table(name
="husband",catalog="JPA_One2One_fk")
public class Husband implements Serializable{
    
    
private int id;
    
private String name;
    
private Wife wife;
    @Id
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
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;
    }
    @OneToOne(mappedBy
="husband")
    
public Wife getWife() {
        
return wife;
    }
    
public void setWife(Wife wife) {
        
this.wife = wife;
    }
    
}
Wife
package com.ono2one.bean;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@SuppressWarnings(
"serial")
@Entity
@Table(name
="wife",catalog="JPA_One2One_fk")
public class Wife implements Serializable{

    
private int id;
    
private String name;
    
private Husband husband;
    @Id
    @GeneratedValue(strategy
=GenerationType.AUTO)
    
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;
    }
    @OneToOne(cascade
=CascadeType.ALL)
    @JoinColumn(name
="husband_id")
    
public Husband getHusband() {
        
return husband;
    }
    
public void setHusband(Husband husband) {
        
this.husband = husband;
    }
    
}
JPAUtil
package com.ono2one.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil {
    
    
private static EntityManager entityManager;
    
public static EntityManager getInstance(){
        
if(entityManager!=null){
            
return entityManager;
        }
else{
            
return makeInstance();
        }
    }
    
private static synchronized EntityManager makeInstance() {
        
if(entityManager==null){
            EntityManagerFactory entityManagerFactory
=Persistence.createEntityManagerFactory("JPA_One2One_fkPU");
            
return entityManagerFactory.createEntityManager();
        }
        
return null;
    }
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version="1.0">
    
    
<persistence-unit name="JPA_One2One_fkPU" transaction-type="RESOURCE_LOCAL">
        
<provider>org.hibernate.ejb.HibernatePersistence</provider>
        
<class>com.ono2one.bean.Husband</class>
        
<class>com.ono2one.bean.Wife</class>
          
<properties>
            
<property name = "hibernate.connection.driver_class" value = "com.mysql.jdbc.Driver"/>
            
<property name = "hibernate.connection.url" value = "jdbc:mysql://localhost:3306/JPA_One2One_pk"/>
            
<property name = "hibernate.connection.username" value = "root"/>
            
<property name = "hibernate.connection.password" value = "root"/>
            
<property name="hibernate.show_sql" value="true"/>
            
<property name="hibernate.format_sql" value="true"/>
          
</properties>
    
</persistence-unit>
  
</persistence>
HusbandDAO
package com.ono2one.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.junit.Test;

import com.ono2one.bean.Husband;
import com.ono2one.bean.Wife;
import com.ono2one.util.JPAUtil;

public class HusbandDAO {
    
    @Test
    
public void insert(){
        EntityManager entityManager
=JPAUtil.getInstance();
        EntityTransaction entityTransaction
=entityManager.getTransaction();
        
try {
            entityTransaction.begin();
            Husband husband
=new Husband();
            husband.setName(
"张三");
            entityManager.persist(husband);
            Wife wife
=new Wife();
            wife.setName(
"如花");
            wife.setHusband(husband);
            entityManager.persist(wife);
            entityTransaction.commit();
        } 
catch (Exception e) {
            e.printStackTrace();
            entityTransaction.rollback();
        }
    }
}
posted @ 2010-10-14 20:37 雪山飞鹄 阅读(3368) | 评论 (0)编辑 收藏

仅列出标题
共22页: First 上一页 7 8 9 10 11 12 13 14 15 下一页 Last