您可以通过使用 java 设置属性来做到这一点
public class TestHibernate {
public static void main(String arg[]) {
Properties prop= new Properties();
prop.setProperty("hibernate.connection.url", "jdbc:mysql://<your-host>:<your-port>/<your-dbname>");
//You can use any database you want, I had it configured for Postgres
prop.setProperty("dialect", "org.hibernate.dialect.PostgresSQL");
prop.setProperty("hibernate.connection.username", "<your-user>");
prop.setProperty("hibernate.connection.password", "<your-password>");
prop.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
prop.setProperty("show_sql", true); //If you wish to see the generated sql query
SessionFactory sessionFactory = new Configuration().addProperties(prop).buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Customer user = new Customer(); //Note customer is a POJO maps to the customer table in the database.
user.setName("test");
user.setisActive(true);
session.save(user);
session.getTransaction().commit();
session.close();
}
}
@Entity
@Table(name = "customer", uniqueConstraints = {
@UniqueConstraint(columnNames = "customerid")})
public class Customer implements Serializable{
private String name;
private int customerid;
private boolean isActive;
public Customer() {
}
public Customer(String name, int customerId, boolean isActive) {
this.name = name;
this.customerid = customerId;
this.isActive = isActive;
}
/**
* GETTERS
*/
@Column(name = "name", unique = false, nullable = false, length = 100)
public String getname() {
return name;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "customerid", unique = true, nullable = false)
public int getcustomerid() {
return customerid;
}
@Column(name = "isactive", unique = false, nullable = false)
public boolean getisactive() {
return isActive;
}
/**
* SETTERS
*/
public void setname(String name) {
this.name = name;
}
public void setisactive(boolean isActive) {
this.isActive = isActive;
}
}