User.java
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
public class UserDetails {
@Id
private int userId;
@Embedded
private BankAccounts personalAccount;
@AttributeOverrides({ @AttributeOverride(name =
"bankName", column = @Column(name = "Office Bank Name")),
@AttributeOverride(name = "bankNumber", column =
@Column(name = "Office Bank Number")),
@AttributeOverride(name = "bankLocation", column
= @Column(name = "Office Bank Location")) })
private BankAccounts officeAccount;
public BankAccounts getPersonalAccount() {
return personalAccount;
}
public void setPersonalAccount(BankAccounts
personalAccount) {
this.personalAccount = personalAccount;
}
public BankAccounts getOfficeAccount() {
return officeAccount;
}
public void setOfficeAccount(BankAccounts officeAccount) {
this.officeAccount = officeAccount;
}
private String userName;
@Embedded
private Address homeAddress;
@AttributeOverrides({ @AttributeOverride(name = "street",
column = @Column(name = "OfficeStreet")),
@AttributeOverride(name = "city", column =
@Column(name = "OfficeCity")),
@AttributeOverride(name = "state", column =
@Column(name = "OfficeState")),
@AttributeOverride(name = "pincode", column =
@Column(name = "OfficePin")) })
private Address officeAddress;
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Address.java
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
@Column (name="STREET")
private String street;
@Column (name="CITY")
private String city;
@Column (name="STATE")
private String state;
@Column (name="PIN")
private String pincode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
BankAccounts.java
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class BankAccounts {
@Column(name="Bank Name")
private String bankName;
@Column(name="Bank Number")
private String bankNumber;
@Column(name="Bank Location")
private String bankLocation;
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBankNumber() {
return bankNumber;
}
public void setBankNumber(String bankNumber) {
this.bankNumber = bankNumber;
}
public String getBankLocation() {
return bankLocation;
}
public void setBankLocation(String bankLocation) {
this.bankLocation = bankLocation;
}
}
SavingUser.java
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import javax.transaction.Transaction;
//import javax.imageio.spi.ServiceRegistry;
import org.hibernate.Session;
import com.hibernate.nithin.dto.Address;
import com.hibernate.nithin.dto.BankAccounts;
import com.hibernate.nithin.dto.UserDetails;
public class SavingUser {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails ud = new UserDetails();
ud.setUserId(1);
ud.setUserName("Nithin Reddy");
Address ad = new Address();
ad.setCity("My City");
ad.setStreet("My Street");
ad.setState("My State");
ad.setPincode("66223");
ud.setHomeAddress(ad);
ad = new Address();
ad.setCity("Office City");
ad.setStreet("Office Street");
ad.setState("Office State");
ad.setPincode("Office Pin");
ud.setOfficeAddress(ad);
BankAccounts bank = new BankAccounts();
bank.setBankName("Personal Bank Name");
bank.setBankLocation("Personal Bank Location");
bank.setBankNumber("Personal Bank Number");
ud.setPersonalAccount(bank);
BankAccounts bank2 = new BankAccounts();
bank2.setBankName("Office Bank Name");
bank2.setBankLocation("Office Bank Location");
bank2.setBankNumber("Office Bank Number");
ud.setOfficeAccount(bank2);
Configuration cfg = new Configuration().configure();
StandardServiceRegistryBuilder builder = new
StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
SessionFactory sf = cfg.buildSessionFactory(builder.build());
Session session = sf.openSession();
org.hibernate.Transaction tx=session.beginTransaction();
System.out.println("is saving");
session.save(ud);
tx.commit();
}
}
的hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/demo?useSSL=false</property>
<property name="connection.username">hibernate</property>
<property name="connection.password">hibernate</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<property name="hbm2ddl.auto">create</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<mapping class="com.hibernate.nithin.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
输出如下。 sql查询正在由hibernate执行,但问题在于保存值。如果我删除所有BankAccount属性和对象但不删除它们
,这样可以正常工作 log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: drop table if exists UserDetails
Hibernate: create table UserDetails (userId integer not null, CITY varchar(255), PIN varchar(255), STATE varchar(255), STREET varchar(255), Office Bank Location varchar(255), Office Bank Name varchar(255), Office Bank Number varchar(255), OfficeCity varchar(255), OfficePin varchar(255), OfficeState varchar(255), OfficeStreet varchar(255), Bank Location varchar(255), Bank Name varchar(255), Bank Number varchar(255), userName varchar(255), primary key (userId))
is saving
Hibernate: insert into UserDetails (CITY, PIN, STATE, STREET, Office Bank Location, Office Bank Name, Office Bank Number, OfficeCity, OfficePin, OfficeState, OfficeStreet, Bank Location, Bank Name, Bank Number, userName, userId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at com.hibernate.nithin.SavingUser.main(SavingUser.java:64)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Bank Location, Office Bank Name, Office Bank Number, OfficeCity, OfficePin, Offi' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2350)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 13 more
答案 0 :(得分:0)
您需要转义包含空格的列名。例如:
@AttributeOverride(name="bankName", column=@Column(name = "`Office Bank Name`"))