只有在网址不存在的情况下,SQL / Hibernate才会插入

时间:2020-07-01 13:43:35

标签: java sql hibernate mariadb

我有一个URL列表和一个包含URL的表。我只想在网址不在表格中时插入。

Data in the Table: 
|id | url | ... |
|---| --- | --- |
| 1 | example.com | ... | 

List<String> urls = new ArrayList<>()
urls.add("example.com/");
urls.add("example.com/#");
urls.add("www.example.com/");
urls.add("https://www.example.com/");
urls.add("example.net");

插入后,数据表应包含:

Data in the Table: 
|id | url | ... |
|---| --- | --- |
| 1 | example.com | ... | 
| 2 | example.net | ... |

我当前的尝试是拥有一个findByURL(url):List方法,并为列表中的每个URL调用此方法。如果返回的列表为空,则将url插入表中,但是不幸的是,我的语句在example.com和example.com#

之间有所不同
@Table(name = "url_to_edit")
@NamedQueries({
        @NamedQuery(name= UrlToEdit.FIND_BY_URL, query = "select urlToEdit from UrlToEdit urlToEdit where urlToEdit.url = :url")
})
@NoArgsConstructor
public class UrlToEdit { ... }

在我当前的解决方案中,表格包含以下行:

Data in the Table: 
|id | url | ... |
|---| --- | --- |
| 1 | example.com | ... | 
| 2 | example.com/ | ... | 
| 3 | example.com/# | ... | 
| 4 | www.example.com/ | ... | 
| 5 | https://www.example.com/ | ... | 
| 6 | example.net | ... | 


我如何在sql中说它是相同的?还是需要某种预解析器? 是否可以批量插入?我当前的代码一个接一个插入。

编辑:我有一台主机有多个URL。我不能追求主机名。 例如example.com/test/ example.com/test/#和example.com/#等。

2 个答案:

答案 0 :(得分:1)

我认为您甚至应该在将URL存储到数据库之前对其进行转换;这样,您的所有数据都将被标准化,您将不必手动检查每一行。对表中的url列使用UNIQUE约束也有帮助。

关于转换,我认为(不确定)以下正则表达式可能有效:

 Pattern URL_REGEX = Pattern.compile("(?:https?:\\/\\/)?(www\\.)?([^\\/]+).*");
 String url = "http://www.example.com/xxx";
 Matcher matcher = URG_REGEX.matcher(url);
 if (matcher.matches()) {
    url = matcher.group(2);
 } 

注意:为了适应您的数据,我对正则表达式进行了调整,但我不会认为example.comwww.example.com是相同的URL。

答案 1 :(得分:0)

也许您可以使用以下方法查看之前是否存在:

select count(urlToEdit) from UrlToEdit urlToEdit where urlToEdit.url like %:url%

如果计数器为零,则可以插入