以下是我为数组中每个电话号码保存消息的编码 在测试中,我已将消息设为欢迎使用所有和5个电话号码进入SMSDTO
如何为数据库中的每个电话号码保存欢迎使用所有消息
1欢迎来到所有9964289813 2欢迎所有9593754589 3欢迎所有9964289444 4欢迎所有9964458454
Pojo课程
@Entity
@Table(name = "sms")
public class SMSDTO {
@Id
@GenericGenerator(name = "j", strategy = "increment")
@GeneratedValue(generator = "j")
@Column(name = "id")
private int id;
@Column(name = "message")
private String message;
@Column(name = "phoneNumber")
private String[] phonenumebr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String[] getPhonenumebr() {
return phonenumebr;
}
public void setPhonenumebr(String[] phonenumebr) {
this.phonenumebr = phonenumebr;
}
}
主要课程
public class Test {
public static void main(String[] args) {
SMSDTO sms = new SMSDTO();
String [] sArry=new String[] { "9964289813", "9591237001", "8722922982", "9611704698", "9900598503" };
Configuration c = new Configuration();
c.configure("/hibernate.cfg.xml");
SessionFactory sf = c.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
try {
for (int i = 0; i < sArry.length; i++) {
sms.setMessage("welcome to All");
sms.setPhonenumebr(sArry[i]);
s.save(sms);
}
tx.commit();
} catch (Exception e) {
tx.rollback();
}
}
}
答案 0 :(得分:0)
更改 POJO 课程,如下所示:
private String phonenumebr;
public String getPhonenumebr() {
return phonenumebr;
}
public void setPhonenumebr(String phonenumebr) {
this.phonenumebr = phonenumebr;
}
只需将private String[] phonenumebr;
更改为private String phonenumebr;
,因为您有一个String数组,稍后您将在主程序中设置单个值phoneNumber。这可以使用String类型的phonenumebr存储,因为String是一个字符数组。
更改主要方法,如下所示:
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
Configuration c = new Configuration();
c.configure("/hibernate.cfg.xml");
SessionFactory sf = c.buildSessionFactory();
session = sf.openSession();
SMSDTO sms =null;
String [] sArry=new String[] { "9964289813", "9591237001", "8722922982", "9611704698", "9900598503" };
tx = session.beginTransaction();
for (int i = 0; i < sArry.length; i++) {
sms= new SMSDTO();
sms.setMessage("welcome to All");
sms.setPhonenumebr(sArry[i]);
session.save(sms);
}
tx.commit();
} catch (RuntimeException e) {
try {
tx.rollback();
} catch (RuntimeException rbe) {
System.err.println("Couldn’t roll back transaction"+ rbe);
}
throw e;
} finally{
if(session != null){
session.close();
}
}
System.out.println("entries saved...");
}
输出: